开发者

C++ typename and inner classes

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.


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
};


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜