ed**********@gmail.com wrote:
Can anyone see anything wrong with the following code?
(CONTAINER can be list, vector, set, ...)
template <class T> void Destroy(T * p) { delete p; }
void CleanUp(std::CONTAINER<ContainerType *> & Container)
{
std::foreach(Container.begin(), Container.end(),
Destroy<ContainerType>);
Container.clear();
}
Sorry for my english,
In your Cleanup function, where do you define the formal parameter of
your template ?
To erase a item collection, you can use a functor.
Look my struct template 'Destroy', with this declaration (and definition).
template <typename T> struct Destroy {
void operator () (T pointer) {
std::cout << "Destroy of this pointer" << std::endl;
delete pointer;
pointer = 0;
}
};
Here, you must to define the type of your container :
The type is detected by the instantiation of your template.
template <typename Container> void CleanUp (Container & pContainer) {
std::for_each (
pContainer.begin (),
pContainer.end (),
Destroy<typename Container::value_type> ());
}
in your main function :
int main (int argc, char **argv) {
std::vector <std::string *> vect;
vect.push_back (new std::string ("Stephane"));
CleanUp (vect);
}
Best regards,
Stephane