接受任何 STL 容器的函数
Function which accept any STL container
我需要实现一个接受任何STL容器的模板函数。并基于执行某些操作的容器类型。
例:
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
}
您可以应用Constexpr If(自 C++17 起((使用std::is_same
(在编译时检查类型,并应用参数包(自 C++11 起(,因为这些容器采用多个模板参数。
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:这取决于您的意图,但是将参数更改为通过引用传递到常量以避免不必要的复制可能是个好主意。
由于无论如何都要为每个容器进行一个实现,因此可以直接进行重载。它将在 C++11 中工作,并且具有在每个重载中轻松提供模板参数的好处。
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
相关文章:
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 在C应用程序中运行C++(带有STL)函数
- 检查函数返回类型是否与STL容器类型值相同
- STL算法函数在多个一维容器上的使用
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 有没有办法捕获 STL 函数未被赋予正确参数的异常?
- 如何在 STL 函数中找到传递给谓词的元素的索引?
- 不能对类型化模板使用 STL 函数
- 如何使用 binary_search STL 函数在嵌套类中搜索整数?
- C++ 如何将参数传递给 STL 函数
- 如何将 STL 队列推送函数绑定到 std::函数?
- STL 函数和函数类型与函数指针类型
- 接受任何 STL 容器的函数
- 重载 STL 函数
- 为什么 stl 字符串C++函数有时出错有时会出错?
- 如何将元素从 STL 队列传递到函数?
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- C++如何获取传递给函数(STL 迭代器)的参数的名称
- 为什么 STL 函数使用节点的颜色来计算 std::map 节点前身