Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function which accept any STL container

Tags:

c++

templates

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
}
like image 872
Yaniboze Avatar asked Apr 18 '26 13:04

Yaniboze


1 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.

like image 161
songyuanyao Avatar answered Apr 20 '26 03:04

songyuanyao