c++ - 接收通用 map 作为参数的模板函数

标签 c++ c++11 templates stdmap template-templates

在很多情况下,我们希望对完全相同的 std::mapstd::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::mapstd::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/

相关文章:

c++ - 使用 ref-qualifiers 解决重载问题

c++ - 对包含索引小部件的 QTableView 列进行排序

javascript - Node.js、哈巴狗模板

c++ - 函数模板和迭代器

c++ - 使用模板特化和接口(interface)对实例和原始类型进行统一函数调用

java - 从 C++ 调用 Java 方法的最简单方法是什么?

c++ - 从控制台应用程序动态使用 DLL

c++ - 更改范围的字符格式

c++ - 线程库的奇怪行为

c++ - 为什么 std::pair 对 const 引用和转发引用参数有两个不同的构造函数?