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?
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.