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
基础教程推荐
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
