The typename keyword

The typename keyword is used to force a dependent name to be treated as a type. For example, consider the following code:

template <class T>
class C1
{
    T::U* v_;
};

The default behaviour of the compiler is not to see T::U as a type, but instead to see it as the name of a variable, making the * symbol a syntax error. The addition of the typename keyword gives the compiler the necessary hint to treat it as a type.

template <class T>
class C1
{
    typename T::U* v_;
};

It can be necessary to add typename to function template return values and parameters for the same reason:

template <class T>
typename T::U F(const typename T::V& v)
{
}

Member typedefs can also require it:

template <class T>
class C2
{
    typedef typename T::U V;
};

And it may be needed in template argument lists:

template <class T>
class C3 : public C2<typename T::U>
{
};

An unrelated additional use of the typename keyword is that it may be used instead of the word class in a template parameter list. In this context it is entirely synonymous with the word class. It is just added to give a clearer indication that the template argument may be a primitive type as well as a class.

template <typename T>
class C4
{
};