Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?
I’m learning about template functions. I’m try to implement a static template function that clear a list of pointers. To do it I want to use templates. Its my code:
#include <cstdio>
#include <list>
using namespace std;
class util
{
public:
template <class ARG>
static void CleanPointers(list<ARG> &mylist) {
list<ARG>::iterator it;
for (it = mylist.begin(); it != mylist.end(); it++)
{
ARG obj = (ARG) *it;
delete obj;
}
mylist.clear();
};
util();
~util();
};
int main()
{
list<int*> mylist;
mylist.push_back(new int(1));
mylist.push_back(new int(2));
util::CleanPointers<int*>(mylist);
return 0;
}
I recived follow compile error message and I dont understand what is the point here. 🙂 Why need I put ; before it?
prog.cpp: In static member function ‘static void util::CleanPointers(std::list<ARG, std::allocator<_Tp1> >&)’:
prog.cpp:10: error: expected `;' before ‘it’
prog.cpp:11: error: ‘it’ was not declared in this scope
prog.cpp: In static member function ‘static void util::CleanPointers(std::list<ARG, std::allocator<_Tp1> >&) [with ARG = int*]’:
prog.cpp:28: instantiated from here
prog.cpp:10: error: dependent-name ‘std::list::iterator’ is parsed as a non-type, but instantiation yields a type
prog.cpp:10: note: say ‘typename std::list::iterator’ if a type is meant
needs typename, thus:
This is not the only thing wrong with the code though. Why are you casting to int before deleting? That is a bad bad bug when it is not a collection of pointers to ints. You should delete through the proper pointer type if you are going to do it this way.
In addition you could put in a partial-specialisation since ARG has to be a pointer type.
C++ FAQ about templates. I would suggest reading all of that.
Also refer to the FAQ about why casts are evil, and it might also explain what happens with delete.