Possible Duplicate:
Where and why do I have to put “template” and “typename” on dependent names?
This is a specific instance of the question: Officially, what is typename for?
I am asking for the specific reason that the compiler is NOT aware that the following is a type:
#include <set>
#include <vector>
template<typename T> // T is a type, right?
void f(const char name[], const std::vector<T>& foo) // typename NOT needed here
{
for(std::set<T>::iterator itr = // here, it is needed
If I declare:
std::set<int>::iterator itr; // no problem
The above clearly defines that T is a type, so why is typename required in one and not the other?
While you’ve links to a thorough answer, it’s a lot to wade through. So – put as simply as I can – the point is that the compiler does indeed know that
Tis a type as you say, but using that information and even having seen the included source code forstd::set, it can’t be sure whether theiteratoridentifier inside theset<T>will name a type, a function, or a variable. This might seem surprising as if you look at theset<>template you can work it out, but remember that somewhere between the compiler parsing yourf<>()template and before it’s instantiated, a specialisation forset<T>may be specified that uses identifier for a non-type, or simply lacks it altogether.So, the
typenamekeyword just tells the compiler, hey – whatever happens you can expectiteratorto name a type, and perform some validatition of thef<>()template code on that basis without waiting to see an instantiation.