【问题标题】:Template inheritance inner class access problem模板继承内部类访问问题
【发布时间】:2011-08-26 04:58:36
【问题描述】:

我不敢相信 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'
    }
};

【问题讨论】:

  • 我已经编辑了这个问题,以便更清楚地了解问题所在。最初听起来您是从内部类继承的,并且问题中的任何地方(但代码)都没有提到模板,而它们是手头的实际问题。

标签: c++ class templates inheritance


【解决方案1】:

问题在于 MyStruct 是一个依赖名称,因此您必须告诉编译器推迟名称查找,直到模板通过使用基类名称限定模板被实例化:

typename BaseClass<T>::MyStruct ms1;

有关更多信息,我会阅读 Parashift C++ 常见问题解答条目,"Why am I getting errors when my template-derived-class uses a nested type it inherits from its template-base-class?"

【讨论】:

    【解决方案2】:
    BaseClass<T>::MyStruct ms3;
    

    应该是

    typename BaseClass<T>::MyStruct ms3;
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多