我遇到了最奇怪的错误,我不知道我做错了什么。
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; }
但为什么?
答案 0 :(得分:2)
编译器不知道如何查找x
。使用this->X
即可使用。
在编译器首次通过struct B
时,模板参数未知。通过使用this
指针,您将推迟名称查找,直到第二次传递。