问题
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