有什么方法可以让我创建一个函数,该函数将具有特定类型的容器(比如 std::string
)作为参数
void foo(const std::container<std::string> &cont)
{
for(std::string val: cont) {
std::cout << val << std::endl;
}
}
并为每种类型的 STL 容器调用它作为输入?像上面一样?
std::set<std::string> strset;
std::vector<std::string> strvec;
std::list<std::string> strlist;
foo(strset);
foo(strvec);
foo(strlist);
最佳答案
您可以制作 foo
一个函数模板采用 template template parameter对于容器类型。
例如
template<template<typename...> typename C>
void foo(const C<std::string> &cont)
{
for(std::string val: cont) {
std::cout << val << std::endl;
}
}
LIVE
关于c++ - 具有特定类型作为泛型参数的 STL 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60297482/