A quick summary of typename
The typename
keyword has two meanings in C++. typename
can be used as a substitute for class
in template parameter lists.
// These two lines mean exactly the same thing.
template<typename A> class Foo {};
template<class A> class Foo {};
The other reason is more complicated. typename
tells a compiler that a dependent name is in fact a type.
Consider:
template<typename T>
struct Bar
{
typedef T MyType; // Okay.
typedef T::Type OtherType; // Wrong.
};
This is wrong because the compiler thinks that T::Type
is not in fact a type, so the typedef
fails. T
might define Type
as something that's not a type (like a static member), so the compiler must default to treating T::Type
as a non-type since it doesn't know what T
is until it is instantiated. In this situation, T::Type
is what standardese calls a dependent name. Note that T
is a non-dependent name because the compiler knows that T
is in fact a type (it's one of the template type parameters), so that doesn't require typename
.
In this case, you must give a hint to the compiler:
template<typename T>
struct Bar
{
typedef T MyType; // Okay.
typedef typename T::Type OtherType; // Okay.
};
Unfortunately, due to compiler bugs, a compiler may compile the snippet without typename
without errors, even though it is not legal!