Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member from base class template not found [duplicate]

Tags:

c++

templates

Possible Duplicate:
Why do I have to access template base class members through the this pointer?

I have a class hierarchy like the following:

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

template<typename T>
class Derived: public Base<T> {
public:
    T get() { return t; }
};

int main() {
    Derived<int> d;
    d.get();
}

The problem is that the protected member variable t is not found in the Base class. Compiler output:

prog.cpp: In member function 'T Derived<T>::get()':
prog.cpp:10:22: error: 't' was not declared in this scope

Is that correct compiler behavior or just a compiler bug? If it is correct, why is it so? What is the best workaround?

Using fully qualified name works, but it seems to be unnecessarily verbose:

T get() { return Base<T>::t; }
like image 504
Juraj Blaho Avatar asked Nov 12 '12 11:11

Juraj Blaho


1 Answers

To use members from template base classes, you have to prefix with this->.

template<typename T>
class Derived: public Base<T> {
public:
    T get() { return this->t; }
};
like image 128
R. Martinho Fernandes Avatar answered Nov 18 '22 10:11

R. Martinho Fernandes