using iterator in template function

W

wuych

I have a question about using iterator in template function

//*****code starts here*****************************
#include <vector>
using std::vector;

template<typename T> void foo( vector<T> & a )
{
vector<T>::iterator i; // ERROR, can't use iterator
}

int main()
{
vector<int> a;
foo(a);
}
//******code ends here ****************************
//****** compiler: gcc 4.1.3 ************************

Can anyone tell me why it's not allowed to use the iterator this way?
Maybe the best way is to use Iterator directly as STL does.
template<typename Iter> void foo(Iter b, Iter e);
Thank you.
 
P

Pete Becker

I have a question about using iterator in template function

//*****code starts here*****************************
#include <vector>
using std::vector;

template<typename T> void foo( vector<T> & a )
{
vector<T>::iterator i; // ERROR, can't use iterator
}

int main()
{
vector<int> a;
foo(a);
}
//******code ends here ****************************
//****** compiler: gcc 4.1.3 ************************

Can anyone tell me why it's not allowed to use the iterator this way?

vector<T>::iterator is what's known as a "dependent name". Its meaning
might be different for different types T (although a program that
specialized vector<Whatever> and made iterator the name of a data
object would be quite perverse). So the rule is that you have to tell
the compiler that vector<T>::iterator names a type:

typename vector said:
Maybe the best way is to use Iterator directly as STL does.
template<typename Iter> void foo(Iter b, Iter e);

Maybe. That way your algorithm can operate on any sequence, and not
just on a vector. That's what most of the standard library algorithms
do. But it depends on what that function is actually doing.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,585
Members
45,082
Latest member
KetonaraKetoACV

Latest Threads

Top