包含std :: vector的boost :: tuple的哈希值

时间:2016-04-29 11:15:44

标签: c++ c++11 boost vector hash

我有这段代码:

template <typename ReturnType, typename... Args>
function<ReturnType(Args...)> memoize(const function<ReturnType(Args...)>& func)
{
    using noRef = boost::tuple<typename std::remove_reference<Args>::type...>;
    ...
    static unordered_map<noRef, ReturnType> cache;
    auto result = cache.emplace(
        noRef{ boost::make_tuple(args ...) }, ReturnType{});
    if (result.second) { //ALWAYS TRUE WITH vector!
    ...

我定义了这两个专门用于计算boost::tuplestd::vector的哈希值:

namespace boost {
    namespace tuples {

        namespace detail {

            template <class Tuple, size_t Index = length<Tuple>::value - 1>
            struct HashValueImpl
            {
                static void apply(size_t& seed, Tuple const& tuple)
                {
                    HashValueImpl<Tuple, Index - 1>::apply(seed, tuple);
                    boost::hash_combine(seed, tuple.get<Index>());
                }
            };

            template <class Tuple>
            struct HashValueImpl<Tuple, 0>
            {
                static void apply(size_t& seed, Tuple const& tuple)
                {
                    boost::hash_combine(seed, tuple.get<0>());
                }
            };
        } // namespace detail

        template <class Tuple>
        size_t hash_value(Tuple const& tuple)
        {
            size_t seed = 0;
            detail::HashValueImpl<Tuple>::apply(seed, tuple);
            return seed;
        }

    }
}

namespace std {
    template <typename T> struct hash<std::vector<T>>
    {
        size_t operator()(const std::vector<T>  & v) const
        {
            size_t seed = 0;
            for (auto it = v.begin(); it != v.end(); it++)
                boost::hash_combine(seed, *it);
            return seed;
            /* your code here, e.g. "return hash<int>()(x.value);" */
        }
    };
}

这是我第一次尝试编写自定义哈希,但是(正如您在注释中看到的那样)即使我总是使用相同的vector<T>,也总是有成功的插入,而它工作正常如果我总是使用相同的double,double

为什么会这样?

0 个答案:

没有答案