繁体   English   中英

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

[英]Specializing std::hash for templated Key

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

我是基于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 specializations应该提供成员类型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;
        }
    };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM