const int*& vs typedef int* IntPtr

3
为什么我需要将int * 更改为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;
};

我了解为什么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 *&)'

你能否发布一下代码,就像在它无法编译时的那样? - hcarver
我会检查这段代码是否能够复现问题(应该可以)。我目前正在使用MSVC 2008编译器。 - John Leidegren
@MvG,是的,那不是这样的,虽然显然是错误的...我刚在MSVC 2008编译器中运行了上面的代码,我想知道为什么“*”会有所不同,它只是一种类型,不是吗? - John Leidegren
正如约翰所提到的,应该是 void foo(int * const &); - Igor R.
1个回答

13

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

如果您写

void foo(int * const &);

不过,它应该能够编译并正常工作。


5
当然,这就是为什么你应该始终在后面放置“const”的原因。如果你写“IntPtr const”,那么很明显这不是“int const*”,而是“int *const”。 - James Kanze

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接