Ambiguous type reference

限于喜欢 提交于 2020-06-17 03:01:53

问题


Why does this works :

template <typename T> 
struct foo
{
};

struct A
{
    typedef foo<A> type;
};

struct B : public A
{
    typedef foo<B> type;
};

int main()
{
    B::type john;
    return 0;
}

But not this :

template <typename T> 
struct foo
{
};

template <typename T>
struct Shared
{
    typedef foo<T> type;
};

struct A : public Shared<A>
{
};

struct B : public A, public Shared<B>
{
};

int main()
{
    // g++ 4.5 says :
    // error: reference to 'type' is ambiguous
    B::type john;
    return 0;
}

In my code, foo is actually boost::shared_ptr and, as you can see, I'm trying so factor some typedefs using a Shared class.


回答1:


Because B inherits foo<B> and, indirectly, foo<A>, and both contain a member type. Which did you mean?

Your simple, first piece of code has B's type hiding A's type, but that doesn't happen in the more complex second piece of code, which involves a deeper inheritance tree.




回答2:


Because you actually have 2 type typedefs. One from A, which gets his from shared<A> and one from shared<B>. In your first case, you hide the type typedef of the A base class with the typedef in B.



来源:https://stackoverflow.com/questions/5445299/ambiguous-type-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!