2

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?

Community
  • 1
  • 1
Dov
  • 6,731
  • 5
  • 35
  • 58

1 Answers1

4

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.

Tony Delroy
  • 94,554
  • 11
  • 158
  • 229
  • thanks! I also noticed that I don't know how to escape angle brackets in a question.... I wonder if < > will do it... – Dov May 19 '11 at 17:26
  • +1 for this : *"on that basis without waiting to see an instantiation."*. – Nawaz May 19 '11 at 17:29
  • @Dov: that stuff's tricky at first... just use back ticks (left single quotes) around source code mixed into normal text, and when you've got a whole line or block of source code just leave a blank line before and after and make sure it's indented by four or more spaces.... Cheers. – Tony Delroy May 19 '11 at 17:44