我无法相信 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'
}
};
答案 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?