0

Could anyone explain why am I not able to use C++ templates like this:

template <typename T> class A {
public:
    typedef std::vector<T>::iterator myiterator;

    A(T value)
        :   v(10, value)
    {
    }

    myiterator begin()
    {
        return v.begin();
    }

    myiterator end()
    {
        return v.end();
    }

public:
    std::vector<T> v;
};

int main()
{
    A<int> a(10);

    for (auto i = a.begin(); i != a.end(); ++i)
        std::cout << *i << std::endl;

    return 0;
}

I got the compilation error on the line where myiterator alias is declared; the error is: "missing ';' before identifier 'myiterator'".

Aleksei Petrenko
  • 6,698
  • 10
  • 53
  • 87

3 Answers3

4

Change

typedef std::vector<T>::iterator myiterator;

to

typedef typename std::vector<T>::iterator myiterator;

Since you are accessing a type through a templated type (vector) you need to help the compiler to disambiguate. vector<T>::iterator could be either a static member, or a type. Without more knowledge of T the compiler cannot be sure. Using the typename keyword there tells the compiler "treat this as a type."

For more details, see Where and why do I have to put the "template" and "typename" keywords?

Community
  • 1
  • 1
bstamour
  • 7,746
  • 1
  • 26
  • 39
  • Yeah, this works! But why the 'typedef' is not enough here? Why should I specify the extra typename keyword? – Aleksei Petrenko Oct 10 '13 at 14:47
  • 1
    C++ is a complex monster, that's why ;) Any time you want to access a type that is dependent on a template parameter, you need `typename`. – bstamour Oct 10 '13 at 14:49
2

Compiler should know std::vector is a type, it's dependent scope:

typedef typename std::vector<T>::iterator myiterator;
masoud
  • 55,379
  • 16
  • 141
  • 208
1

I get the helpful error message:

 'std::vector<T>::iterator' : dependent name is not a type
          prefix with 'typename' to indicate a type

You need to tell it you are declaring a type:

typedef typename std::vector<T>::iterator myiterator;
//      ^^^^^^^^
doctorlove
  • 18,872
  • 2
  • 46
  • 62