继承模板阴影继承成员

时间:2017-09-17 20:32:00

标签: c++ c++11 templates inheritance

我遇到了最奇怪的错误,我不知道我做错了什么。

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; }

但为什么?

1 个答案:

答案 0 :(得分:2)

编译器不知道如何查找x。使用this->X即可使用。

在编译器首次通过struct B时,模板参数未知。通过使用this指针,您将推迟名称查找,直到第二次传递。