非库类型的无序key_type需要散列<>专业化?

时间:2012-11-21 23:33:54

标签: c++ c++11 unordered-map xerces-c

我正在尝试使用xercesc :: XMLUri作为键类型创建一个std :: unordered_map。

#include <unordered_map>
#include "xercesc/util/XMLUri.hpp"

int main()
{
        std::unordered_map<xercesc::XMLUri,xercesc::XMLUri> uriMap;
}

产生以下结果:

clang++ -std=c++11 -O0 -emit-llvm -g3 -Wall -c -fmessage-length=0 -I/usr/include ../xx.cpp 
In file included from ../xx.cpp:1:
In file included from /usr/bin/../lib/gcc/i686-linux-gnu/4.7/../../../../include/c++/4.7/unordered_map:43:
/usr/bin/../lib/gcc/i686-linux-gnu/4.7/../../../../include/c++/4.7/bits/functional_hash.h:59:7: error: static_assert failed "std::hash is not specialized for this type"
  static_assert(sizeof(_Tp) < 0,
  ^             ~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/i686-linux-gnu/4.7/../../../../include/c++/4.7/bits/unordered_map.h:45:32: note: in instantiation of template class 'std::hash<xercesc_3_1::XMLUri>' requested here
                       integral_constant<bool, !__is_final(_Hash)>,
                                                ^
/usr/bin/../lib/gcc/i686-linux-gnu/4.7/../../../../include/c++/4.7/bits/unordered_map.h:263:14: note: in instantiation of default argument for '__unordered_map<xercesc_3_1::XMLUri, xercesc_3_1::XMLUri, std::hash<xercesc_3_1::XMLUri>, std::equal_to<xercesc_3_1::XMLUri>, std::allocator<std::pair<const xercesc_3_1::XMLUri, xercesc_3_1::XMLUri> > >' required here
: public __unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../xx.cpp:6:54: note: in instantiation of template class 'std::unordered_map<xercesc_3_1::XMLUri, xercesc_3_1::XMLUri, std::hash<xercesc_3_1::XMLUri>, std::equal_to<xercesc_3_1::XMLUri>, std::allocator<std::pair<const xercesc_3_1::XMLUri, xercesc_3_1::XMLUri> > >' requested here
    std::unordered_map<xercesc::XMLUri,xercesc::XMLUri> uriMap;

我知道C ++ 0x中的无序容器只为某些库类型提供hash<>个特性。如何为hash<xercesc::XMLUri>创建所需的xercesc::XMLUri专精?

编辑:我想出了这个。这看起来合理吗?

#include "xercesc\util\XMLUri.hpp"
#include <string>

namespace std 
{

    size_t hash<xercesc::XMLUri>::operator()(const xercesc::XMLUri& uri) const
    {
        return hash<std::wstring>()(uri.getUriText());
    }
}

2 个答案:

答案 0 :(得分:1)

几乎。它应该是这样的(感谢@jogojapan指出缺少的typedef!):

#include <string>
#include <functional>

namespace std
{
    template <> struct hash<xercesc::XMLUri>
    {
        typedef size_t result_type;
        typedef xercesc::XMLUri argument_type;

        size_t operator()(xercesc::XMLUri const & uri) const noexcept
        {
            return hash<wstring>()(uri.getUriText());
        }
    };
}

答案 1 :(得分:1)

std::hash是一个结构,你必须专注于整个结构,而不仅仅是函数,那么你专门化模板的方式也是错误的:

namespace std 
{
    template <>
    struct hash<xercesc::XMLUri>
    {
        size_t operator()(const xercesc::XMLUri& uri) const
        {
            return hash<std::wstring>()(uri.getUriText());
        }
    };
}