【问题标题】:boost::uuids::uuid as a key in std::unordered_map?boost::uuids::uuid 作为 std::unordered_map 中的键?
【发布时间】:2013-05-04 11:26:08
【问题描述】:

我在 Mac OS X 上使用 clang (CXX='clang++ -std=c++11 -stdlib=libc++'),boost 1.53.0。

我想在 unordered_map 中使用 uuid 作为键,但出现以下错误:

/usr/bin/../lib/c++/v1/type_traits:748:38: error: implicit instantiation of undefined template
      'std::__1::hash<boost::uuids::uuid>'
    : public integral_constant<bool, __is_empty(_Tp)> {};
                                 ^
/usr/bin/../lib/c++/v1/unordered_map:327:54: note: in instantiation of template class
      'std::__1::is_empty<std::__1::hash<boost::uuids::uuid> >' requested here
template <class _Key, class _Tp, class _Hash, bool = is_empty<_Hash>::value

...

/usr/bin/../lib/c++/v1/unordered_map:327:71: error: no member named 'value' in
      'std::__1::is_empty<std::__1::hash<boost::uuids::uuid> >'
template <class _Key, class _Tp, class _Hash, bool = is_empty<_Hash>::value
                                                     ~~~~~~~~~~~~~~~~~^

...

这是什么 - Boost 中的一个错误,导致它与我的 C++ 库不兼容?或者我做错了什么?有什么解决方法吗?

【问题讨论】:

    标签: c++ boost clang boost-uuid


    【解决方案1】:

    为什么在 boost 中出现错误?您应该将std::hash 模板专门用于boost::uuid

    #include <boost/functional/hash.hpp>
    
    namespace std
    {
    
    template<>
    struct hash<boost::uuids::uuid>
    {
        size_t operator () (const boost::uuids::uuid& uid)
        {
            return boost::hash<boost::uuids::uuid>()(uid);
        }
    };
    
    }
    

    或者,只需使用boost::hash par 创建unordered_map

    std::unordered_map<boost::uuids::uuid, T, boost::hash<boost::uuids::uuid>>
    

    或提供满足std::hash 要求的hash 函子(感谢Praetorian)。

    【讨论】:

    • +1 除了提供std::hash 的显式特化之外,您还可以创建一个类型(例如uuid_hasher)并实现uuid_hasher::operator()(uuid const&amp;)。该类型将成为unordered_map 的第三个模板参数
    • 我认为 operator() 的 hash 对您的类型的专业化需要标记为 const。将其保留为非 const 无法编译。
    猜你喜欢
    • 2018-12-20
    • 2012-06-01
    • 2012-10-07
    • 2012-07-09
    • 2018-07-09
    • 1970-01-01
    • 2012-05-23
    • 2016-08-23
    • 2020-03-09
    相关资源
    最近更新 更多