模糊类型参考

时间:2011-03-26 21:04:25

标签: c++ templates typedef multiple-inheritance

为什么会这样:

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

但不是这样:

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

在我的代码中,foo实际上是boost::shared_ptr,正如您所看到的,我正在尝试使用typedef类对某些Shared进行处理。

2 个答案:

答案 0 :(得分:4)

因为B继承foo<B>,间接地继承foo<A>,并且都包含成员type。你是什​​么意思?

您的简单第一段代码B type 隐藏 A的{​​{1}},但这不会发生在更复杂的第二段代码中,它涉及更深层的继承树。

答案 1 :(得分:1)

因为你实际上有2个type typedef。一个来自A,来自shared<A>,一个来自shared<B>。在第一种情况下,您使用type中的typedef隐藏A基类的B typedef。

相关问题