2012-08-02 92 views
3

为什么我必须将int *更改为typedef int * IntPtr才能编译?const int *&vs 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; 
}; 

我明白为什么typedefs是有用的,但不是为什么他们是必需的。类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 *&)' 
+0

你可以发布的代码,因为它不会编译? – Hbcdev 2012-08-02 13:32:44

+0

我会检查这段代码是否会重现问题(它应该)。我目前正在使用MSVC 2008编译器。 – 2012-08-02 13:33:58

+3

'do'是一个关键字! – MvG 2012-08-02 13:37:38

回答

13

const int*&typedef int* IntPtr; const IntPtr&是不一样的。在第一种情况下,它的int是常量,在第二种情况下它是指针。只有第二种情况与您的模板兼容。

如果你写

void foo(int * const &); 

相反,它应该编译和工作得很好。

+5

当然,这是为什么你总是应该在'const'之后。如果你写了'IntPtr const',很明显这不是'int const *',而是'int * const'。 – 2012-08-02 13:39:00