gpt4 book ai didi

c++ - 为模板化 key 专门化 std::hash

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:34:15 26 4
gpt4 key购买 nike

我试图为我自己的类型专门化哈希,一个模板化的键。

我是基于 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);
}
};
}

最佳答案

您的代码存在一些问题:

不允许将新的定义或声明放入std 命名空间;只允许特化(例如 std::hash)。因此,您的 MyKey 模板应该移出 std 命名空间。

您的 operator() 签名不正确。 MyKey 没有命名类型,您需要明确地参数化它。此外,运算符应标记为 const

std::hash 特化应提供成员类型 argument_typeresult_type

如果作为 SType 等传入的类型没有现成的特化,您需要自己提供。

您不会从哈希函数返回任何内容,只是计算其他类型的哈希值并丢弃它们的返回值。

将为具有自己的 std::hash 特化的类型编译的实现:

//moved out of std
template<typename SType, typename AType, typename PType>
struct MyKey {
const SType from;
const AType consume;
const PType pop;
};

namespace std {
template<typename SType, typename AType, typename PType>
struct hash<MyKey<SType, AType, PType>>{
//member types
using argument_type = MyKey<SType,AType,PType>;
//arguments specified ^ ^ ^
using result_type = std::size_t;

result_type operator ()(argument_type const& key) const {
//marked const ^
//these will fail if SType and friends don't have a std::hash specialization
result_type s_hash = std::hash<SType>()(key.from);
result_type a_hash = std::hash<AType>()(key.consume);
result_type p_hash = std::hash<PType>()(key.pop);

//in your actual code, you'll want to compute the return type from the above
return p_hash;
}
};
}

关于c++ - 为模板化 key 专门化 std::hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29893095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com