Typeid inside the template class does not work

I have a problem with the following code:

template <typename U> class lamePtr { public: typedef U* ptr; }; template <typename U> class smarterPointer { public: void funFun() { typedef lamePtr<U> someType; someType::ptr query; } }; 

As you can see, I have a typedef inside lamePtr. Inside the smarterPointer class, I have a funFun () function. I am trying to make another typedef someType. Until this line, everything works fine until we go to the line asking for someType :: ptr.

What I want here is that the "request" will become lamePtr <U> :: ptr (a simple value, not a typedef;). However, I get compilation errors (with gcc 4.4.3):

 temp.cpp: In member function 'void smarterPointer&ltU>::funFun()': temp.cpp:15: error: expected ';' before 'query' 

What am I doing wrong here?

+7
source share
2 answers

someType since lamePtr<U> is a "dependent name". It depends on what U refers to if there is a ptr member, and if so, which β€œthing” belongs to that member.

Of course, you know that for all T , lamePtr<T>::ptr is a type, but the parser does not know this at this stage of compilation.

Use the typename keyword to hint at the parser that it is a type. The rest will be resolved later in the compilation process. Just a little C ++ quirk.

 template <typename U> class lamePtr { public: typedef U* ptr; }; template <typename U> class smarterPointer { public: void funFun() { typedef lamePtr<U> someType; typename someType::ptr query; } }; 
+12
source

You need the typename keyword to indicate that someType::ptr is a type.

  typename someType::ptr query; 

See Officially, what is typename for? for details.

+9
source

All Articles