专门用于模板化密钥的std :: hash

Ran*_*own 6 c++ hash templates c++11 stdhash

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

我是基于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);
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

Tar*_*ama 4

您的代码存在一些问题:

不允许您将新的定义或声明放入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;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)