7

テンプレート化されたキーである独自のタイプのハッシュを特殊化しようとしていました。

私はそれを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);
        }
    };
}
4

1 に答える 1

4

コードにはいくつかの問題があります。

新しい定義または宣言をstd名前空間に配置することは許可されていません。特殊化 ( などstd::hash) のみが許可されます。したがって、MyKeyテンプレートはstd名前空間の外に移動する必要があります。

あなたのoperator()署名は間違っています。MyKeyタイプに名前を付けないため、明示的にパラメータ化する必要があります。さらに、オペレータには マークを付ける必要がありますconst

std::hash特殊化は、メンバーの型argument_typeとを提供する必要がありresult_typeます。

as などで渡された型の特殊化が存在しない場合は、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;
        }
    };
}
于 2015-04-27T10:43:32.840 に答える