模板继承内部类访问问题

时间:2011-05-16 06:16:57

标签: c++ class templates inheritance

我无法相信 gcc 不接受以下代码...请告诉我,如果从基本模板访问内部类是不可能的,或者我错过了什么?

template <class T> class BaseClass
{
public:
    struct MyStruct
    {
        T *data;
    };
};

template <class T> class ChildClass : public BaseClass <T>
{
    public:

    void problem()
    {
        MyStruct ms1; //error: 'MyStruct' was not declared in this scope
        ::MyStruct ms2; //error: '::MyStruct' has not been declared
        BaseClass<T>::MyStruct ms3; //error: expected `;' before 'ms3'
    }
};

2 个答案:

答案 0 :(得分:15)

问题是MyStruct是一个依赖名称,所以你必须告诉编译器推迟名称查找,直到模板通过用基类名称限定来实例化:

typename BaseClass<T>::MyStruct ms1;

有关详细信息,请阅读Parashift C ++ FAQ条目"Why am I getting errors when my template-derived-class uses a nested type it inherits from its template-base-class?"

答案 1 :(得分:6)

BaseClass<T>::MyStruct ms3;

应该是

typename BaseClass<T>::MyStruct ms3;

由于MyStruct是一个从属名称,即它取决于模板参数 相关:Where and why do I have to put “template” and “typename” on dependent names?