以下代码不能用 gcc 编译,但可以用 Visual Studio 编译:
template <typename T> class A {
public:
T foo;
};
template <typename T> class B: public A <T> {
public:
void bar() { cout << foo << endl; }
};
我得到错误:
test.cpp: In member function ‘void B::bar()’:
test.cpp:11: error: ‘foo’ was not declared in this scope
但它应该是!如果我将 bar
更改为
void bar() { cout << this->foo << endl; }
然后它确实编译,但我不认为我必须这样做。 GCC 在此处遵循的 C++ 官方规范中是否有某些内容,还是只是一个怪癖?
最佳答案
大卫乔伊纳有历史,这就是原因。
编译时的问题B<T>
是它的基类A<T>
对于编译器来说是未知的,是一个模板类,所以编译器无法知道基类中的任何成员。
早期版本通过实际解析基本模板类进行了一些推断,但 ISO C++ 声明这种推断可能会导致不应存在的冲突。
在模板中引用基类成员的解决方案是使用 this
(就像你做的那样)或专门命名基类:
template <typename T> class A {
public:
T foo;
};
template <typename T> class B: public A <T> {
public:
void bar() { cout << A<T>::foo << endl; }
};
更多信息见 gcc manual .
关于c++ - GCC 问题 : using a member of a base class that depends on a template argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11405/