可能有很多情况下,我们想要在与映射类型无关的std::map
或std::unordered_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使用模板的模板。什么是正确的方法来做到这一点?
['std :: map'](http://en.cppreference.com/w/cpp/container/map)有两个以上的模板参数。你还有一个'比较'类型和'Allocator'类型。你必须指定所有的,甚至是默认的。 –
请注意,您的代码将正常工作来C++ 17;以下解决方案都适用于C++ 14及更低版本。 –