我遇到了最奇怪的错误,我不知道我做错了什么。
template <bool X>
struct A {
int x;
};
template <bool X>
struct B : public A<X> {
B() { x = 3; } // Error: 'x' was not declared in this scope.
};
我不明白我怎么可能看不到 x
来自B
,鉴于我正在继承 A
公开。
同时,这段代码编译通过:
template <bool X>
struct A {
int x;
};
template <bool X>
struct B : public A<X> {};
int main() {
B<false> b;
b.x = 4;
};
我正在使用 g++ 7.0.1 进行编译。
编辑:似乎如果我引用 x
的全名,代码编译,如下所示:
B() { A<X>::x = 3; }
但是为什么呢?
最佳答案
编译器不知道如何找到x
。使用 this->X
就可以了。
当编译器第一次遍历struct B
时,模板参数是未知的。通过使用 this
指针,您可以将名称查找推迟到第二遍。
关于c++ - 使用模板继承影子继承成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46268613/