在 gcc 中,存在继承关系的模版类,子类无法直接访问父类的成员,即使该成员是protected
或public
。
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
下编译。
另外,这个错误只有在Derived
和Base
都是模版类时才会出现,这两者任何一个不是模版类,都不会出现编译错误。
2、原因
原因据说是因为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.