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

时间:2015-04-27 10:23:43

标签: c++ templates c++11 hash stdhash

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

我的基础是cppreference

我收到编译错误" C ++标准没有提供此类型的哈希值#34;。我想我做错了。编译器甚至可以支持这种模板吗?

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);
        }
    };
}

1 个答案:

答案 0 :(得分: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;
        }
    };
}