小编And*_*ldo的帖子

用于接收通用映射作为参数的模板函数

可能存在许多情况,其中我们想要在a std::mapstd::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;
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试编译上面的例子,我有这个:

error: no matching function for call to ‘printMap(std::map<int, long int>&)’
Run Code Online (Sandbox Code Playgroud)

我在这篇文章中读到了模板模板的使用.这样做的正确方法是什么?

c++ templates stdmap template-templates c++11

4
推荐指数
2
解决办法
2198
查看次数

标签 统计

c++ ×1

c++11 ×1

stdmap ×1

template-templates ×1

templates ×1