Dependent names vs non-dependent names

In the following example:

template<typename T>
struct MyList {
    typedef std::list<T> type1;

template<typename T>
class MyList2 {
    typename MyList<T>::type1 type2;

I thought that both type1 and type2 are dependent name since both of their types depend on the template parameter. However, why is the first one considered non-dependent since I can use typedef with it?

>Solution :

A dependent name is, in C++ terms, a name whose grammatical properties are dependent on a template parameter.

Names can mean a lot of different things in C++, and the grammatical location where a name can be used depends on certain properties of that name. In order to understand what X x; is trying to do, the compiler needs to know what X is at this point in the program. If X names a type, then this is declaring a variable named x. The compiler doesn’t need to know everything about X, but grammatically, in order to even begin to make sense of this text, the compiler does need to know that X here names a type.

std::list is the name of a class template; the compiler can easily see that because that’s how it is declared. It doesn’t need to have the body of the declaration; template<typename T> class list; is sufficient. std::list<T> is an instantiation of a class template, so just from the declaration, the compiler knows that this is the name of a type.

However, MyList<T>::type1 now requires more than just the declaration of the MyList template. It requires actually instantiating that template. And if T is itself a template parameter of the current code (as is the case for MyList2), then instantiation at the point of initially compiling the code is impossible. That instantiation must be delayed until MyList2 is itself given a concrete T to work with.

But the compiler still has to make sense of this code: typename MyList<T>::type1 type2;. And to do that, it needs some idea of what MyList<T>::type1 actually is. Without instantiating MyList<T>.

Which is why you have to tell it that it is a typename.

Leave a Reply