在很多情况下,我们希望对完全相同的 std::map
或 std::unordered_map
执行一些操作,独立于 map 的类型。让我们考虑以下示例:
#include <map>
#include <unordered_map>
#include <iostream>
template< template <typename,typename> class Container >
void printMap(Container<int, long> inputMap, bool additionalParam = false)
{
for (const pair<int,long> p : inputMap)
cout<<p.first <<","<< p.second <<std::endl;
}
int main()
{
int a = 1;
long b = 2;
map<int,long> map1;
map1.emplace(a,b);
unordered_map<int,long> map2;
map2.emplace(a,b);
printMap(map1);
printMap(map2);
return EXIT_SUCCESS;
}
如果我尝试编译上面的例子,我有这个:
error: no matching function for call to ‘printMap(std::map<int, long int>&)’
我在这个 post 中读到了模板的模板的使用.正确的做法是什么?
最佳答案
尝试
template< template <typename...> class Container, typename ... Ts >
void printMap(Container<int, long, Ts...> inputMap,
bool additionalParam = false)
代码中的(更大)问题是 std::map
和 std::unordered_map
是具有四个(而不是两个)模板参数的模板类。第 3 个和第 4 个具有默认值,因此您可以将 std::map
对象定义为
std::map<int, long> map1;
但是,使用默认参数,您将其定义为
std::map<int, long, std::less<int>,
std::allocator<std::pair<const int, long> >> map1;
(ps:或者您可以简化它并使用 auto
,如 Semyon Burov 的解决方案;+1)
关于c++ - 接收通用 map 作为参数的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45601144/