Template help needed
-
I do this over and over and I can't figure out how to make this function into a template.
void CleanUpVector() { std::vector::iterator iter; for (iter = vMusic.begin(); iter != vMusic.end(); ++iter) { delete *iter; } vMusic.clear(); } struct TAG { string TrackNumber; string Title; string Artist; string Genre; string Year; string Comment; string Album; string PersistsAs; }; struct Music_Item { HSTREAM Stream; TAG Tag; };
Any ideas anyone? I can't figure this out.
-
I do this over and over and I can't figure out how to make this function into a template.
void CleanUpVector() { std::vector::iterator iter; for (iter = vMusic.begin(); iter != vMusic.end(); ++iter) { delete *iter; } vMusic.clear(); } struct TAG { string TrackNumber; string Title; string Artist; string Genre; string Year; string Comment; string Album; string PersistsAs; }; struct Music_Item { HSTREAM Stream; TAG Tag; };
Any ideas anyone? I can't figure this out.
You really don't want to be doing this - it's asking for trouble. You'd be much better using something like boost::shared_ptr in the vector rather than raw pointers - then, if required you can pass custom deleters into the function. Below is an example of a template function which does what you requested. Depending on usage the call to clear() may be redundant, or may not do what you expected.
template<class T> void cleaner(std::vector<T>& v) { typedef typename std::vector<T>::iterator iter; iter cur(v.begin()); iter end(v.end()); for(; cur != end; ++cur) { delete (*cur); } v.clear(); }
EDIT: fixed typo
-
You really don't want to be doing this - it's asking for trouble. You'd be much better using something like boost::shared_ptr in the vector rather than raw pointers - then, if required you can pass custom deleters into the function. Below is an example of a template function which does what you requested. Depending on usage the call to clear() may be redundant, or may not do what you expected.
template<class T> void cleaner(std::vector<T>& v) { typedef typename std::vector<T>::iterator iter; iter cur(v.begin()); iter end(v.end()); for(; cur != end; ++cur) { delete (*cur); } v.clear(); }
EDIT: fixed typo
Thanks that worked great. This is the part I couldn't figure out.
typedef typename std::vector::iterator iter; iter cur(v.begin()); iter end(v.end());