I need to implement a template function that accepts any STL container. And based on what kind of container to perform certain actions.
Example:
template <class Container, class T>
void func(Container<T> container) {
if (container == std::map) {
...
} else {
...
}
}
int main() {
std::vector<int> v1;
func(v1); // ok
std::vector<double> v2;
func(v2); // ok
std::map<int, double> m1;
func(m1); // ok
std::list<int> l1;
func(l1); // ok
}
You can apply Constexpr If (since C++17) (with std::is_same) to check the type at compile-time, and apply parameter pack (since C++11) because these containers take multiple template parameters. e.g.
template <template <typename...> class Container, class... T>
void func(const Container<T...>& container) {
if constexpr (std::is_same_v<Container<T...>, std::map<T...>>) {
...
} else if constexpr (std::is_same_v<Container<T...>, std::vector<T...>>) {
...
} else if constexpr (std::is_same_v<Container<T...>, std::list<T...>>) {
...
} else {
...
}
}
PS: It depends on your intent but changing the parameter to pass-by-reference-to-const to avoid unnecessary copy might be a good idea.
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