无法访问模板基类中的变量

Ria*_*iaD 2 c++ inheritance templates g++

我想在父类中访问受保护的变量,我有以下代码,并且可以正常编译:

class Base
{
protected:
    int a;
};

class Child : protected Base
{
public:
    int b;
    void foo(){
        b = a;
    }
};

int main() {
    Child c;
    c.foo();
}
Run Code Online (Sandbox Code Playgroud)

好的,现在我想将所有内容都模板化。我将代码更改为以下内容

template<typename T>
class Base
{
protected:
    int a;
};

template <typename T>
class Child : protected Base<T>
{
public:
    int b;
    void foo(){
        b = a;
    }
};

int main() {
    Child<int> c;
    c.foo();
}
Run Code Online (Sandbox Code Playgroud)

并得到错误:

test.cpp: In member function ‘void Child<T>::foo()’:
test.cpp:14:17: error: ‘a’ was not declared in this scope
             b = a;
                 ^
Run Code Online (Sandbox Code Playgroud)

这是正确的行为吗?有什么不同?

我使用g ++ 4.9.1

Lig*_*ica 6

呵呵,我最喜欢的C ++古怪!

这将起作用:

void foo()
{
   b = this->a;
//     ^^^^^^
}
Run Code Online (Sandbox Code Playgroud)

不合格的查询在这里不起作用,因为该库是模板。就是这样,并且归结为有关如何翻译C ++程序的高度技术细节。