I need to make a template function that receives as parameter a std::container of some type - let's say std::vector and deletes all elements from that container. I need a function equivalent to this:
for_each(some_vector.begin(), some_vector.end(), [](some_vector_type* element){delete element;});
The call should be something like:
delete_all_elements(some_vector);
Is this possible?
EDIT: I want to use first code inside delete_all_elements
vector is a template class, which can be instantiated with a type, in the format: vector<int> , vector<double> , vector<string> . The same template class can be used to handle many types, instead of repeatably writing codes for each of the type.
Vectors, or std::vector , are a template class in the STL (Standard Template Library). But what does that mean? They are a more flexible, refined, and efficient replacement for arrays, which are used in the C programming language (and on which the C++ language is based).
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>( float original ); Template arguments may be omitted when the compiler can infer them.
Why wouldn't it be?
template <typename C>
void delete_all_elements(C& container) {
std::for_each(
container.begin(), container.end(),
[](typename C::value_type ptr) { delete ptr; }
);
container.clear();
}
You can add e.g. static_assert(std::is_pointer<typename C::value_type>::value, "Elements must be pointers");
at the beginning to ensure you won't try to delete non-pointers.
Why not do something like virtually every STL algorithm:
template<typename Iterator>
void delete_all_elements(Iterator begin, Iterator end) {
while (begin != end) {
delete *begin;
++begin;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With