using STL iterators inside a template function

Hello to everyone, I need to create a template function that iterate items of a list and save all items in a file. This is what I wrote:

template <class ItemClass>
int Controller::
saveItemsToFile ( list<ItemClass> &_itemsList, const string &filename )
{
int ni = -1;
ofstream outfile ( filename.c_str(), ios_base::out );
if ( !outfile )
cerr << "saveItemsToFile:: unable to open file" << endl;
else
{
ni++;
list<ItemClass>::iterator _nhit = _itemsList.begin();
list<ItemClass>::iterator _nhend = _itemsList.end();
while ( _nhit != _nhend )
{
outfile << *_nhit;
if ( outfile.fail() )
{
cerr << "saveItemsToFile:: file writing error!" << endl;
break;
}
_nhit++;
ni++;
}
outfile.close();
}
return ni;
}

But when I try to compile it I get an error saying
error: need ‘typename’ before ‘std::list<U>::iterator’ because ‘std::list<U>’ is a dependent scope.
So I can't iterate a list inside my template function or there is another way to do it?
Thank you for your help.
Last edited on
Did you even read the error message? Oo
need ‘typename’ before ‘std::list<U>::iterator’ because ‘std::list<U>’ is a dependent scope.


Also, don't name your variables with an underscore as the first character, those are reserved.
I guess the compliler doesn't still know what could be objected for "ItemClass" since it's only a template in the compiling phase, only can be initiated in run-time.

Try:
"
typedef typename list<ItemClass>::iterator MyIt;
"
before declaring _nhit.


b2ee
Last edited on
Thank you for your help, I solved by declaring _nhit and _nhend in this way:

typename list<ItemClass>::iterator _nhit = _itemsList.begin();
typename list<ItemClass>::iterator _nhend = _itemsList.end();

Topic archived. No new replies allowed.