2

Possible Duplicate:
Base template class data members are not visible in derived template class?

I am trying to create a templated class that extends a templated super-class.

template <class T>
class SuperClass {
public:
        T my_data;
};

template <typename T2>
class SubClass : public SuperClass<T2>
{
public:
        T2 f() { return my_data; }
};

int main()
{
        SubClass<int> x;
        return 0;
}

However, I get the following error (using g++ 4.6.1):

test.cpp:11:18: error: ‘my_data’ was not declared in this scope

Strangely, it works if I redefine SubClass::f() as follows:

T2 f() { return this->my_data; }

Does anyone understand why I need to have a this->?

Community
  • 1
  • 1
user1031921
  • 146
  • 2
  • 8

2 Answers2

4

Names not depending on a template argument are looked up in context of the template being defined when it doesn't, yet, know the template arguments. The name my_data doesn't depend on the template argument at all. Names somehow depending on a template argument, e.g. because they must refer to a member of a template class, are looked up in phase 2 when the template arguments are known. The name this->my_data clearly depends on the template argument and is, thus, looked up in phase 2. These are the basic rules for two phase name-lookup in templates.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
1

This behaviour is due to [temp.dep]/3:

In the definition of a class or class template, if a base class depends on a template-parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.

Mankarse
  • 39,818
  • 11
  • 97
  • 141