Possible Duplicate:
Officially, what is typename for?
Where and why do I have to put the template and typename keywords?
consider the code below:
template<class K>
class C {
struct P {};
vector<P> vec;
void f();
};
template<class K> void C<K>::f() {
typename vector<P>::iterator p = vec.begin();
}
Why is the "typename" keyword necessary in this example? Are there any other cases where "typename" must be specified?
Short answer: Whenever referring to a nested name that is a dependent name, i.e. nested inside a template instance with unknown parameter.
Long answer: There are three tiers of entities in C++: values, types, and templates. All of those can have names, and the name alone doesn't tell you which tier of entity it is. Rather, the information about the nature of a name's entity must be inferred from the context.
Whenever this inference is impossible, you have to specify it:
Here the names
Magic<T>::gnarl
,Magic<T>::brugh
andMagic<T>::kwpq
had to be expliciated, because it is impossible to tell: SinceMagic
is a template, the very nature of the typeMagic<T>
depends onT
-- there may be specializations which are entirely different from the primary template, for example.What makes
Magic<T>::gnarl
a dependent name is the fact that we're inside a template definition, whereT
is unknown. Had we usedMagic<int>
, this would be different, since the compiler knows (you promise!) the full definition ofMagic<int>
.(If you want to test this yourself, here's a sample definition of
Magic
that you can use. Pardon the use ofconstexpr
in the specializaation for brevity; if you have an old compiler, feel free to change the static member constant declaration to the old-style pre-C++11 form.)Usage: