1

The following code fails to compile (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;
}

The error is as follows:

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

By my understanding, B<T> should have access to protected members of its parent class. Why does B<T> not see the protected member A<T>::t_?

alcedine
  • 909
  • 5
  • 18

1 Answers1

0

Because the base class A<T> is dependent on tempalate parameter T, then is a dependent base class, and t_ is a nondependent name, which is not looked up in dependent base class.

You can make t_ dependent to solve the issue, e.g.

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

or

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

or

T get() { 
    using A<T>::t_;
    return *t_; 
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405