3

When trying to access type alias in a base class from derived class, I am facing the following issue:

template <typename T>
class A {
    public:
        using T2 = T;
};

template <typename T>
class B: public A<T> {
    public:
        typename A<T>::T2 obj1;  // OK
        T2 obj2;  // Error
};

template <typename T>
class C: public A<int> {
    public:
        typename A<int>::T2 obj1;  // OK
        T2 obj2;  // OK
};

I am unable to understand why does initializing the base class with an explicit type lets us access the type alias in the base class but in the first case, it leads to an error.

Thanks in advance.

nims
  • 3,751
  • 1
  • 23
  • 27

1 Answers1

5

T2 is a nondependent name. Nondependent names won't be looked up in dependent base classes like A<T>, which depends on the template parameter T.

A<T>::T2 works, it's dependent name. Dependent names can be looked up only at the time of instantiation, and at that time the exact base specialization that must be explored will be known.

On the other hand, when the base class is A<int> the code works because A<int> is a nondependent base class and the nondependent name T2 would be found at the scope of A<int>.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405