1

Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?

This is reproduced from Stroustroup's FAQ. I've seen typename used when you don't know the type, for instance in templates, template <typename> class some_class. Why is typename used in the example below?

    template<class T> void printall(const vector<T>& v)
    {
        for (auto p = v.begin(); p!=v.end(); ++p)
            cout << *p << "\n";
    }

In C++98, we'd have to write 

    template<class T> void printall(const vector<T>& v)
    {
        for (typename vector<T>::const_iterator p = v.begin(); p!=v.end(); ++p)
            cout << *p << "\n";
    }
Community
  • 1
  • 1

1 Answers1

1

Your example is exactly the typical example. Since vector<T> is used with a templated parameter T we have to tell the compiler that ::const_iterator is a type. This is there to help the compiler to know that for any T the vector<T> type has a type named const_iterator.

Johan Lundberg
  • 23,281
  • 9
  • 67
  • 91
  • So the iterator depends upon not only the container type but what it holds..that is an iterator for vector is different than an iterator for vector? –  Feb 27 '12 at 19:12
  • vector is completely specified so the compiler can just use it like any other type at that point. – Johan Lundberg Feb 27 '12 at 19:14
  • @GuyMontag - compiler cannot know that `vector::const_iterator` is a type at all. It could be a method or a static data member, and the compiler won't know until it creates a concrete type from the `vector` template. – Robᵩ Feb 27 '12 at 19:18