Why does the word 'typedef' need 'typename' after it for dependent types?

c++, typedef, typename

Solution

`typedef` does not need to appear before the type.

template <typename T>
struct S { typedef T type; };
template <typename T>
void f() { typename S<T>::type typedef t; }

This is perfectly valid, and in this case, I hope you can understand that parsing would be complicated if `typename` were optional.

I can understand that

template <typename T>
void f() { typedef S<T>::type t; }

could be interpreted differently, but that would introduce unexpected cases where the position of the `typedef` keyword suddenly becomes significant.

Problem

Dependent types generally need `typename` to tell the compiler the member is a type, not a function or variable. However, this is not always the case. For example, a base class doesn't require this, because it can only ever be a type: ``` template<class T> struct identity { typedef T type; } template<class T> class Vector : identity<vector<T> >::type { }; // no typename ``` Now my question is, why does `typedef` ever require `typename` after it? ``` template<class T> class Vector { typedef typename /* <-- why do we need this? */ vector<T>::iterator iterator; }; ```

Original source