为什么B类<t>没有看到父类A <t>的受保护成员?

时间:2017-03-30 06:28:42

标签: c++ templates

以下代码无法编译(ideone):

#include <iostream>

template <typename T>
class A {
public:
    A(T* t) : t_(t) {}

protected:
    T* t_;
};

template <typename T>
class B : public A<T> {
public:
    B(T* t) : A<T>(t) {}

    T get() { return *t_; }
};

int main()
{
    int i = 4;
    B<int> b(&i);
    std::cout << b.get() << std::endl;
}

错误如下:

prog.cpp:17:20: error: use of undeclared identifier 't_'
        T get() { return *t_; }
                          ^

据我了解,B<T>应该可以访问其父类的受保护成员。为什么B<T>看不到受保护的成员A<T>::t_

1 个答案:

答案 0 :(得分:0)

因为基类A<T>依赖于tempalate参数T,所以它是一个从属基类,而t_是一个非依赖名称,在依赖基类中没有查找

您可以让t_依赖于解决问题,例如

T get() { return *this->t_; }

T get() { return *A<T>::t_; }

T get() { 
    using A<T>::t_;
    return *t_; 
}