15

In C++, I am trying to get a std::vector::iterator for my templated class. However, when I compile it, I get the errors: error C2146: syntax error : missing ';' before identifier 'iterator', error C4430: missing type specifier - int assumed. Note: C++ does not support default-int. I also get the warning: warning C4346: 'std::vector<T>::iterator' : dependent name is not a type:

#include <vector>
template<class T> class v1{
    typedef std::vector<T>::iterator iterator; // Error here
};
class v2{
    typedef std::vector<int>::iterator iterator; // (This works)
};

I have even tried

template<typename T> class v1{
    typedef std::vector<T>::iterator iterator;
};

And

template<typename T = int> class v1{
    typedef std::vector<T>::iterator iterator;
};
Joe
  • 1,059
  • 2
  • 11
  • 21
  • possible duplicate of [Where and why do I have to put the "template" and "typename" keywords?](http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords) – juanchopanza Jan 05 '14 at 13:52
  • 1
    clang++ is known to have quite decent error messages, especially for these kind of errors. In this case, it says *error: missing 'typename' prior to dependent type name 'std::vector::iterator'*. I recommend trying clang (e.g. in an online compiler) if you can't understand the error message from another compiler. – dyp Jan 05 '14 at 14:05
  • @DyP GCC has similar error messages. – Rapptz Jan 05 '14 at 14:12
  • @Rapptz Oh, indeed it has for this example :) well that's a surprise. I eventually switched from g++ to clang++ some time ago because the error messages became unreadable, albeit for more complicated cases. – dyp Jan 05 '14 at 14:18

1 Answers1

34

std::vector<T>::iterator is a dependent name, so you need a typename here to specify that it refers to a type. Otherwise it is assumed to refer to a non-type:

typedef typename std::vector<T>::iterator iterator;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480