tags:

views:

82

answers:

2

I tried googling this, but I was unable to come up with a suitable answer. Could any C++ gurus tell me why C++ requires you to declare OuterClass<T>::Innerclass with the typename keyword?

I am a TA for a data structures course and I see this error all of the time. I know to tell my students that they need to put typename in front of the return type, but I am unable to explain why this is required.

Thanks.

+6  A: 

OuterClass<T>::Innerclass

That because Innerclass represents a type (as I can see from your question) so you need to add the keyword typename before OuterClass<T>::Innerclass

Example :

template <class T>
void foo() {
   T::iterator * iter;
   ...
}

Without typename T::iterator * iter; would be interpreted as multiplication operation between T::iterator and iter

Prasoon Saurav
Actually the reason is that the compiler cannot determine this information (due to templates) at the point when he needs it.
Let_Me_Be
@Let_Me_Be: The compiler knows how it is supposed to interpret the code. It can't determine the programmer's *intention*. And then there's VC++ that doesn't check dependent names and works things out when the template is intantiated. VC++ should be able to produce both a multiplication and a pointer declaration from the same function under suitable conditions :)
UncleBens
+5  A: 

That's because of the two-phase name lookup in templates. When the compiler sees Innerclass it must know whether that name is a type or not (is could, for example, be a static member of type int for some specialization of OuterClass). So it supposes it is NOT a type name unless you say so. typename must be used in templates and only on names dependent on the template parameter. HTH

example:

template <class T>
class X
{ 
   typedef T XXX;
};
template<>
class X<char>
{
   static int XXX;
};

template<class T>
class Y
{        
   // X<T>::XXX member; invalid XXX is not assumed to be a type! 
   typename X<T>::XXX member; 
   //we explicitly specify that XXX is a type; Later, upon instantiation, we will verify that
};
Armen Tsirunyan