Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL container with a specific type as a generic argument

Tags:

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); 
like image 987
chatzich Avatar asked Feb 19 '20 09:02

chatzich


People also ask

Which of the following are STL containers types?

The three types of containers found in the STL are sequential, associative and unordered.

What are the types of STL containers in C++?

In C++, there are generally 3 kinds of STL containers: Sequential Containers. Associative Containers. Unordered Associative Containers.


1 Answers

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

like image 200
songyuanyao Avatar answered Sep 22 '22 15:09

songyuanyao