我正在尝试在派生类中使用模板化基类的成员变量,如本例所示:
template <class dtype>
struct A {
int x;
};
template <class dtype>
struct B : public A<dtype> {
void test() {
int id1 = this->x; // always works
int id2 = A<dtype>::x; // always works
int id3 = B::x; // always works
int id4 = x; // fails in gcc & clang, works in icc and xlc
}
};
gcc 和 clang 都对使用此变量非常挑剔,并且需要明确的范围或明确使用“this”。对于其他一些编译器(xlc 和 icc),一切如我所料。这是 xlc 和 icc 允许非标准代码的情况,还是 gcc 和 clang 中的错误?
最佳答案
您可能在 icc 中以非严格模式编译。无论如何,由于 x
是非限定的,因此不应在依赖于模板参数的任何基类中查找它。所以在你的代码中,没有找到x
的地方,你的代码是无效的。
使用另一种形式的查找(类成员访问查找和限定查找)查找其他名称。如果可以的话,这两种形式都会查看依赖基类(即如果它们是依赖的,因此在 dtype
已知时实例化模板时会查找 - 所有其他名称都依赖于模板参数).
即使是最新版本的 GCC 也没有正确实现,一些依赖名称 still resolve against dependent bases在不合格的查找期间。
关于c++ - 使用从模板化基类继承的成员变量 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2738985/