How to specialize std::hash for type from other library(如何为来自其他库的类型专门化 std::hash)
问题描述
所以我使用的库有一个枚举(假设它名为LibEnum).我需要有一个
LibEnum 的
std::unordered_set
,但是我得到编译错误,没有专门的 std::hash
用于它.我可以轻松地编写它并只返回值的数量(第一个元素是 0,第二个元素是 1 等),但是我应该把这个专业化放在哪里,它应该是什么样子的?我无法修改库源.
So the library I use has an enum (say it's named LibEnum
). I need to have an std::unordered_set
of LibEnum
, but I get compilation error that there is no specialized std::hash
for it. I could easily write it and just return the number of value (first element is 0, second 1 etc), but where exactly I should put this specialization and how should it look like? I can't modify the library sources.
enum LibEnum { A, B, C, D};
std::unordered_set <LibEnum> mySet;
//need std::hash for LibEnum
//how should it look like?
推荐答案
你可以专门针对你的类型std::hash
:
You can just specialise std::hash
for your type:
namespace std {
template <>
struct hash<FullyQualified::LibEnum> {
size_t operator ()(FullyQualified::LibEnum value) const {
return static_cast<size_t>(value);
}
};
}
或者,您可以在任何您喜欢的地方定义 hash
类型,并在实例化 std::unordered_map
时将其作为附加模板参数提供::>
Alternatively, you can define a hash
type where ever you like and just provide it as the additional template argument when instantiating std::unordered_map<FooEnum>
:
// Anywhere in your code prior to usage:
struct myhash {
std::size_t operator ()(LibEnum value) const {
return static_cast<std::size_t>(value);
}
};
// Usage:
std::unordered_map<LibEnum, T, myhash> some_hash;
这两种方法都不需要您修改库.
Neither methods require you to modify the library.
这篇关于如何为来自其他库的类型专门化 std::hash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何为来自其他库的类型专门化 std::hash


- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- STL 中有 dereference_iterator 吗? 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01