【问题标题】:Why can't I inhert from a templated superclass in C++? [duplicate]为什么我不能从 C++ 中的模板超类继承? [复制]
【发布时间】:2012-03-20 07:09:00
【问题描述】:

可能重复:
Base template class data members are not visible in derived template class?

我正在尝试创建一个扩展模板化超类的模板化类。

template <class T>
class SuperClass {
public:
        T my_data;
};

template <typename T2>
class SubClass : public SuperClass<T2>
{
public:
        T2 f() { return my_data; }
};

int main()
{
        SubClass<int> x;
        return 0;
}

但是,我收到以下错误(使用 g++ 4.6.1):

test.cpp:11:18: error: ‘my_data’ was not declared in this scope

奇怪的是,如果我重新定义SubClass::f() 如下:

T2 f() { return this->my_data; }

有人明白我为什么需要this-&gt;吗?

【问题讨论】:

    标签: c++ templates inheritance


    【解决方案1】:

    不依赖于模板参数的名称在模板定义的上下文中查找,但它还不知道模板参数。 my_data 这个名字根本不依赖于模板参数。名称以某种方式取决于模板参数,例如因为它们必须引用模板类的成员,所以在模板参数已知的阶段 2 中查找。名称this-&gt;my_data 显然取决于模板参数,因此在阶段 2 中查找。这些是模板中两个阶段名称查找的基本规则。

    【讨论】:

      【解决方案2】:

      这种行为是由于[temp.dep]/3:

      在类或类模板的定义中,如果基类依赖于模板参数,则在非限定名称查找期间,无论是在类模板或成员的定义点还是在类模板或成员的实例化。

      【讨论】:

        猜你喜欢
        • 2019-08-10
        • 2016-07-30
        • 1970-01-01
        • 1970-01-01
        • 2011-05-06
        • 2012-02-07
        • 2010-12-06
        • 1970-01-01
        相关资源
        最近更新 更多