【发布时间】:2015-07-05 17:59:52
【问题描述】:
我试图为我自己的类型专门化散列,一个模板键。
我是基于cppreference。
我收到编译错误“C++ 标准没有为这种类型提供哈希”。我想我只是做错了。编译器还能支持这种模板吗?
namespace std {
template<typename SType, typename AType, typename PType>
struct MyKey {
const SType from;
const AType consume;
const PType pop;
};
template<typename SType, typename AType, typename PType>
struct hash<MyKey<SType, AType, PType>> {
size_t operator ()(MyKey const &key) {
std::hash<SType>()(key.from);
std::hash<AType>()(key.consume);
std::hash<PType>()(key.pop);
}
};
}
【问题讨论】:
-
你必须教编译器如何散列你的类型——不仅仅是
MyKey,还有SType。AType和PType也是(至少那些不是typedefs 的已知类型)。完成之后,MyKey的散列不应该只是调用成员变量的散列函数,它应该返回一个包含这些成员变量散列的hash_combined 值。有 很多 个现有问题可以解释这一点。
标签: c++ templates c++11 hash stdhash