Question

I want to iterate a container inside some template function.If container is deque but type it stores is not known then, I tried:

template <typename T>
void PrintDeque(deque<T> d)
{
    deque<T>::iterator it; //error here
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

OR if I try this for unknown container:

template <typename T>
void PrintDeque(T d)
{
    T::iterator it;   //error here
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

Both give compilation errors. How to create an iterator inside the template function so that I can iterate the container?

Was it helpful?

Solution

template <typename T>
void PrintDeque(T d)
{
    typename T::iterator it;   //error here
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

You need typename before it because the compiler doesn't know you're naming a type, or a static variable. It's called a dependant type.

http://pages.cs.wisc.edu/~driscoll/typename.html

As an aside and to comment on the other answers. Some compilers don't need this, and some do. GCC is one of the compilers that do need this clarification.

OTHER TIPS

You can use this code:

template <typename T>
void PrintDeque(deque<T> d)
{
    deque<T>::iterator it;
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

This code works fine on my windows with vs12.


Note:

template <typename T>
void PrintDeque(deque<T> d)
{
    deque<typename T>::iterator it; //error here
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

this code, what you've posted is also working fine on my computer.

#include <deque>
#include <iostream>
using namespace std;

template<typename range>
void PrintEverythingIn(range C)
{
        for (auto e : C)
                cout << e << ' ';
        cout << endl;
}

deque<int> demo { 1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,20 };

int main() { PrintEverythingIn(demo); }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top