Hi, What is the meaning of "typename" in C++? I never realized there's such a keyword until now. For the following function: template<class T> void clearMap(map<string, T> m) { map<string, T>::const_iterator it = m.begin(); /* X */ for (int i = m.size(); i > 0; i--, ++it) { const string* key = &(it->first); m.erase(*key); delete(key); } } g++ will warn that the declaration of iterator it (line marked with /* X */) is deprecated. But using: typename map<string, T>::const_iterator it = ... will remove the warning. TIA. -- -- Verdi March --
Verdi March wrote:
Hi,
What is the meaning of "typename" in C++? I never realized there's such a keyword until now.
typename tells the compiler to interpret what follows as a type rather than as a function or member. So the compiler would expect map<string, T>::const_iterator to be a static member function or static member variable of the class map<string,T> and generate an error in this case. g++ is clever enough to work out that in this case it cannot be a static member and there is in map<S,T> a typdef const_iterator and so just warns you that you should put in typename. To see why typename is essential, consider the following template<class T> void function( T* t ){ T::const_iterator it = t->begin(); ... } Since this can be compiled without any knowledge of a specific T, the compiler has no way to tell whether T::const_iterator should be a type or a static member. The rule is that it assumes it is a static member and produces a syntax error. If you want to change the interpretation, use typename.
For the following function:
template<class T> void clearMap(map<string, T> m) { map<string, T>::const_iterator it = m.begin(); /* X */ for (int i = m.size(); i > 0; i--, ++it) { const string* key = &(it->first); m.erase(*key); delete(key); } }
g++ will warn that the declaration of iterator it (line marked with /* X */) is deprecated. But using: typename map<string, T>::const_iterator it = ... will remove the warning.
TIA.
-- JDL Non enim propter gloriam, diuicias aut honores pugnamus set propter libertatem solummodo quam Nemo bonus nisi simul cum vita amittit.
participants (2)
-
John Lamb
-
Verdi March