STL::Accessing the iterator for a "passed" container type

  • Thread starter Generic Usenet Account
  • Start date
G

Generic Usenet Account

Hi,

I am passing a container type (e.g. list<int>) to a function template
but I am getting a compiler error when I try to declare an iterator
for that type in the function. However, I am able to invoke begin()
and end() without any problem. Is there a way to declare an iterator
for the container type? Sample code follows.

Thanks,
Ramesh


//////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////
#include <iostream>
#include <list>

using namespace std;

//////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////
template<typename T>
void
access_the_iterator(T& collection)
{
while(collection.begin() != collection.end())
{
cout << "In the loop\n";
}

//T::iterator iter;
// ** Compiler error upon uncommenting **
}


//////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////
main()
{
list<int> coll;
access_the_iterator(coll);
return 0;
}
 
M

Markus Schoder

Hi,

I am passing a container type (e.g. list<int>) to a function template
but I am getting a compiler error when I try to declare an iterator for
that type in the function. However, I am able to invoke begin() and
end() without any problem. Is there a way to declare an iterator for
the container type? Sample code follows.
[snip]

template<typename T>
void
access_the_iterator(T& collection)
{
while(collection.begin() != collection.end()) {
cout << "In the loop\n";
}

//T::iterator iter;

Try

typename T::iterator iter;
 
A

Andre Kostur

Hi,

I am passing a container type (e.g. list<int>) to a function template
but I am getting a compiler error when I try to declare an iterator
for that type in the function. However, I am able to invoke begin()
and end() without any problem. Is there a way to declare an iterator
for the container type? Sample code follows.

That's what is referred to as a dependant type name. You need the
"typename" keyword:

typename T::iterator iter;


C++ needs the hint that T::iterator is a type and not a function or
variable name. (Remember, it doesn't know what T is when it parses that
line)
 

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,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top