为什么模板参数会影响基类中成员的可见性?

时间:2018-11-21 14:22:27

标签: c++

考虑下一个示例:

#include <iostream>

template <int I>
class A {
protected:
    int x = 0;
}; 

template <int I>
class B : public A<I> { 
public:
    void foo() { std::cout << x << std::endl; }
};

int main() {
    B<2> b;
    b.foo();
}

在声明template <int I> OR class A之前,如果没有class B(并进行相应的更改以使代码有效),一切都可以正常编译。 当我使用上面的示例调用g++ test.cpp时,得到以下输出:

test.cpp: In member function ‘void B<I>::foo()’:
test.cpp:13:16: error: ‘x’ was not declared in this scope
   std::cout << x << std::endl;
                ^

奇怪的是,如果我将x替换为this->x,一切都会再次编译。

0 个答案:

没有答案