c++ - 在 C++ 中隐藏不同的 std::map 比较参数

标签 c++ dictionary templates polymorphism

我有一个看起来像这样的类:

template<typename comparer>
class MyClass {
  std::map<std::uint32_t, MyElementType, comparer> entries;
public:
  void doSomething(std::uint32_t key, const MyElementType& el) {
    ...
  }
};

我想在 MyClass 以与特定比较器无关的方式专门针对不同的比较器之后使用它。最优雅的方法是什么?

最佳答案

使用 std::function 作为比较器。

using MyMap = std::map<std::uint32_t, int, std::function<bool(std::uint32_t, std::uint32_t)>>;
MyMap entries1{[](std::uint32_t a, std::uint32_t b){ return a < b; }};
MyMap entries2{[](std::uint32_t a, std::uint32_t b){ return a > b; }};

关于c++ - 在 C++ 中隐藏不同的 std::map 比较参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58571700/

相关文章:

C# 成员变量作用域

templates - Kotlin 中的动态评估模板字符串

c++ - 为什么指针到成员函数的模板参数推导失败?

c++ - C++ 中 unordered_map 的包装类

c++ - 使用初始值设定项列表将 const 数组引用实例化为构造函数参数,是否允许?

c++ - 模板:用类类型的成员实例化一个对象

c++ - 在分析 boost::graph 时,是否对顶点和边描述符或它们的迭代器进行操作?

c++ - 当你不遵循 argv 和 argc 的做法时会发生什么

json - 如何将 JSON 数组转换为 JSON 映射 : one specific array element attribute value becomes the key of each map

javascript - 将 map 经纬度加载到 html 内的脚本不起作用