Search code examples
c++templatesstlcontainers

STL container with a specific type as a generic argument


Is there any way that I can make a function which takes a container with a specific type (lets say std::string) as a parameter

void foo(const std::container<std::string> &cont)
{
   for(std::string val: cont) {
      std::cout << val << std::endl;
   }
}

and call it for every type of stl container as input? like above?

std::set<std::string> strset;
std::vector<std::string> strvec;
std::list<std::string> strlist;

foo(strset);
foo(strvec);
foo(strlist);

Solution

  • You can make foo a function template taking a template template parameter for the container type.

    e.g.

    template<template<typename...> typename C>
    void foo(const C<std::string> &cont)
    {
       for(std::string val: cont) {
          std::cout << val << std::endl;
       }
    }
    

    LIVE