Abhijit
Abhijit

Reputation: 63707

How to create an STL object of iterators of template Type?

How to create an STL object of iterators of template Type? I am trying to create an STL Object (say Vector) of iterators of a template type as below

vector<vector<T>::iterator> it1;

This fails both in g++ and VC++ where. Both the compilers almost says the same thing

g++

Main.cpp:8:49: error: type/value mismatch at argument 1 in template parameter li
st for `template<class _T1, class _T2> struct std::pair'
Main.cpp:8:49: error:   expected a type, got `std::vector<T>::iterator'

VC++

error C2923: 'std::vector' : 'std::vector<T>::iterator' is not a valid template type argument for parameter '_Ty'

Off-course if you are creating an iterator of Concrete Type it works for example

vector<vector<int>::iterator> it1;

Here is a minimum failing example

#include<vector>
#include<iterator>
using namespace std;
template<typename T>
class Spam {
public:
    vector<vector<int>::iterator> it1; #Compiles Fine
    vector<vector<T>::iterator>   it2; #Fails
    };

NOTE

What I understood from the answers is if a type if dependent then one needs to prefix the keywords typename. If that is so then

vector< vector<T>  >  it;

should also fail but it doesn't. It only seems to fail and require a typename keywords iff the dependent name is a typedef

Upvotes: 2

Views: 1752

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361302

You need to use typename as:

vector<typename vector<T>::iterator>   it2; 

It is because iterator is a dependent name, as it depends on the template argument T.

As a sidenote, be aware that iterators of a vector get invalidated when the vector resizes itself. So a vector of such iterators may not be as useful as you might think. To make such a vector useful, make sure that the vector never resizes itself whose iterators you're going to store in this vector of iterators.

Upvotes: 4

This has been asked soon many times...

 vector<typename vector<T>::iterator>

The problem is that the nested type iterator is dependent on the arguments to your template, so you need to tell the compiler that it is a type, or else it will assume that it is a regular template.

Upvotes: 1

Stephan Dollberg
Stephan Dollberg

Reputation: 34518

You have to add the typename keyword:

vector<typename vector<T>::iterator>   it2; 

This page helped me the most to understand it.

Upvotes: 5

Related Questions