0

I need to define a template derived class of a template base class. The question has been asked and answered before (e.g. here), but the accepted solution gives me a compiler error. For example, this code:

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

template<typename T>
class Derived : public Base<T> {
public:
    void f(){
        i = 1;
    }
};

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

give the following errors:

$ g++ test.cpp 
test2.cpp: In member function ‘void Derived<T>::f()’:
test2.cpp:11:9: error: ‘i’ was not declared in this scope
         i = 1;
         ^
$ clang++ test2.cpp 
test2.cpp:11:9: error: use of undeclared identifier 'i'
        i = 1;
        ^
1 error generated.

So it seems like the derived class doesn't see the variable defined in the mother (tested with gcc 7.2.1 and clang 5.0.0). For sure I must be doing something wrong, but I can't figure out what, especially given the fact that in the accepted answer to the question I linked the derived class seems to see the 'counter' variable defined in the mother class. Thanks for the help.

Nicola Mori
  • 777
  • 1
  • 5
  • 19
  • 3
    Try `Base::i = 1;` or `this->i = 1;`. – François Andrieux Dec 13 '17 at 17:37
  • 1
    You'll need to qualify access to members in the base with something depending a template name. You can use `Base::i` or `this->i`: both approaches will work. The problem you encounter is that phase I look-up doesn't find `i` as `i` doesn't depend on a template parameter. Adding the qualification delays look-up until phase II name look-up. – Dietmar Kühl Dec 13 '17 at 17:39
  • Thanks for your help, the proposed solutions work. So I guess that the solution of the question I linked is flawed. If one is willing to write an answer then I'll accept it. – Nicola Mori Dec 13 '17 at 17:45

0 Answers0