Reason for requiring typename in a template definition [duplicate]
Possible Duplicate:
Where开发者_如何学C 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 T
is a type as you say, but using that information and even having seen the included source code for std::set
, it can't be sure whether the iterator
identifier inside the set<T>
will name a type, a function, or a variable. This might seem surprising as if you look at the set<>
template you can work it out, but remember that somewhere between the compiler parsing your f<>()
template and before it's instantiated, a specialisation for set<T>
may be specified that uses identifier for a non-type, or simply lacks it altogether.
So, the typename
keyword just tells the compiler, hey - whatever happens you can expect iterator
to name a type, and perform some validatition of the f<>()
template code on that basis without waiting to see an instantiation.
精彩评论