为什么我必须将其更改int *为a typedef int * IntPtr才能编译?
template <class T>
class A
{
public:
template <class X>
void a(X *x, void (X::*fun)(const T&))
{
}
};
typedef int * IntPtr;
class B
{
public:
B() : a()
{
a.a(this, &B::foo); // this won't work
}
void foo(const int *&) // must replace `int *` here with `IntPtr`
{
}
A<int *> a; // ...and here
};
class C
{
public:
C() : a()
{
a.a(this, &C::foo);
}
void foo(const IntPtr&)
{
}
A<IntPtr> a;
};
Run Code Online (Sandbox Code Playgroud)
我理解为什么typedef是有用的,但不是为什么它们是必需的.这个类C编译好B没有.
这是来自MSVC++ 2008编译器的错误:
Error 1 error C2784: 'void A<T>::a(X *,void (__thiscall X::* )(const T &))' : could not deduce template argument for 'void (__thiscall X::* )(const T &)' from 'void (__thiscall B::* )(const int *&)'
Run Code Online (Sandbox Code Playgroud)
joh*_*ohn 13
const int*&并且typedef int* IntPtr; const IntPtr&不一样.在第一种情况下,它是int常量,在第二种情况下它是指针.只有第二种情况与您的模板兼容.
如果你写
void foo(int * const &);
Run Code Online (Sandbox Code Playgroud)
相反,它应该编译和工作得很好.
| 归档时间: |
|
| 查看次数: |
617 次 |
| 最近记录: |