Re: using iterator in template function
On 2007-11-08 11:10:26 -0500, wuych <yanchun.wu@gmail.com> said:
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<T>::iterator i; // okay
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.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)