const int *& vs typedef int * IntPtr

问题描述:

为什么我必须将 int * 更改为 typedef int * IntPtr

Why is it that I have to change the int * to a typedef int * IntPtr for this to compile?

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;
};



我理解为什么typedef是有用的,但不是为什么它们是必需的。 C $ c> $ c>

I understand why typedefs are useful but not why they are required. the class C compiles fine B does not.

这是MSVC ++ 2008编译器的错误:

This is the error from MSVC++ 2008 compiler:

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 *&)'


const int *& typedef int * IntPtr; const IntPtr& 不一样。在第一种情况下,它的int是常量,在第二种情况下,它是指针。

const int*& and typedef int* IntPtr; const IntPtr& are not the same. In the first case it's the int that's constant, in the second case it's the pointer. Only the second case is compatible with your template.

如果您写

void foo(int * const &);

而是应该编译和工作很好。

instead, it should compile and work just fine.