无法访问模板库中的变量 class

Can't access variable in template base class

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

class Base
{
protected:
    int a;
};

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

int main() {
    Child c;
    c.foo();
}

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

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

出现错误:

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

这是正确的行为吗?有什么区别?

我使用 g++ 4.9.1

呵呵,我最喜欢的 C++ 奇葩!

这会起作用:

void foo()
{
   b = this->a;
//     ^^^^^^
}

非限定查找在这里不起作用,因为基础是模板。 That's just the way it is,并归结为有关如何翻译 C++ 程序的高度技术细节。