5

模版类继承需显示声明子类成员

 3 years ago
source link: https://zhiqiang.org/coding/name-lookup-on-derived-template-class.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在 gcc 中,存在继承关系的模版类,子类无法直接访问父类的成员,即使该成员是protectedpublic

1. 一个简单的例子

#include <iostream> 

template <class  T>
class Base {
public:
    T x;
    Base(T _x) : x(_x) {}
};

template <class T>
class Derived : public Base<T> {
public: 
    Derived(T x) : Base<T>(x) {}
    void log() { 
        std::cout << x << std::endl; 
    }
};

int main()
{
    Derived<int> d(2);
    d.log();
}

gcc编译下会报错:

In member function 'void Derived::log()': 16:22: error: 'x' was not declared in this scope

而且这个错误只会在gcc下出现,vc不会出现该问题。因此,编写跨平台的模版库时,应当去gcc下编译。

另外,这个错误只有在DerivedBase都是模版类时才会出现,这两者任何一个不是模版类,都不会出现编译错误。

原因据说是因为stdandard 14.6/8

When looking for the declaration of a name used in a template definition, the usual lookup rules (3.4.1, 3.4.2) are used for nondependent names. The lookup of names dependent on the template parameters is postponed until the actual template argument is known (14.6.2).

stdandard 16.2是这么说的:

In the definition of a class template or a member of a class template, if a base class of the class template depends on a template-parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.

也就是说gcc的编译报错行为符合c++标准。

3. 解决方案

3.1. 通过子类引用

void log() {
    std::cout << Base<T>::x << std::endl; 
}

3.2. 通过 this 引用

void log() {
    std::cout << this->x << std::endl;
}

3.3. 通过 using 将变量引入子类

using Base<T>::x;
void log() {
    std::cout << x << std::endl;
}

Q. E. D.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK