Function which accept any STL container

Viewed 368

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
}
2 Answers

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.

Since you're making one implementation per container anyway, you could make overloads directly. It'll work in C++11 and has the benefit of having the template parameters easily available in each overload.

template <class T, size_t N>
void func(const std::array<T,N>& c) {
    std::cout << "array " << c.size() << '\n';
}

template <class T, class Alloc>
void func(const std::vector<T,Alloc>& c) {
    std::cout << "vector " << c.size() << '\n';
}

template <class T, class Alloc>
void func(const std::list<T,Alloc>& c) {
    std::cout << "list " << c.size() << '\n';
}

template <class Key, class T, class Comp, class Alloc>
void func(const std::map<Key,T,Comp,Alloc>& c) {
    std::cout << "map " << c.size() << '\n';
}

template <class CharT, class Traits, class Alloc>
void func(const std::basic_string<CharT,Traits,Alloc>& c) {
    std::cout << "basic_string " << c.size() << '\n';
}

// add more of the containers you aim to support here
Related