class A
{
static int iterator;
class iterator
{
[...]
};
[...]
};
I (think I) understand the reason why typename is needed here:
template <class T>
void foo() {
typename T::iterator* iter;
[...]
}
but I don’t understand the reason why typename is not needed here:
void foo() {
A::iterator* iter;
[...]
}
Can anyone explain?
EDIT:
The reason why the compiler does not have a problem with the latter, I found to be answered well in a comment:
in the case of A::iterator I don’t see why the compiler wouldn’t confuse it with the static int iterator ? – xcrypt
@xcrypt because it knows what both A::iterators are and can pick which one depending on how it is used – Seth Carnegie
The reason why the compiler needs typename before the qualified dependent names, is in my opinion answered very well in the accepted answer by Kerrek SB. Be sure to also read the comments on that answer, especially this one by iammilind:
“T::A * x;, this expression can be true for both cases where T::A is a type and T::A is a value. If A is a type, then it will result in pointer declaration; if A is a value, then it will result in multiplication. Thus a single template will have different meaning for 2 different types, which is not acceptable.”
A name in C++ can pertain to three different tiers of entities: Types, values, and templates.
The three names
Foo::A,Foo::BandFoo::Care examples of all three different tiers.In the above example,
Foois a complete type, and so the compiler knows already whatFoo::Aetc. refer to. But now imagine this:Now we are in trouble: what is
T::A? ifT = Foo, thenT::A = int, which is a type, and all is well. But whenT = struct { static char A; };, thenT::Ais a value, which doesn’t make sense.Therefore, the compiler demands that you tell it what
T::AandT::BandT::Care supposed to be. If you say nothing, it is assumed to be a value. If you saytypename, it is a typename, and if you saytemplate, it is a template:Secondary checks such as whether
T::Bis convertible toint, whetheraandxcan be multiplied, and whetherC<int>really has a member functiongobbleare all postponed until you actually instantiate the template. But the specification whether a name denotes a value, a type or a template is fundamental to the syntactic correctness of the code and must be provided right there during the template definition.