在MacOS上的unordered_multimap中为自定义类型定义麻烦的哈希函数

问题描述 投票:0回答:1

所以我想使用自定义类型(此处为SWrapper)作为unordered_multimap的键类型。我定义了一个哈希类,该哈希类派生自标准的字符串哈希函数,并将该哈希类包含在多图类型中。下面显示了一些重现该错误的代码。这可以在具有g ++和clang ++的Arch Linux上编译,但是在具有clang ++的MacOS上,我会收到错误消息:

#include <unordered_map>
#include <functional>
#include <string>

class SWrapper {
    public:
    SWrapper() {
        (*this).name = "";
    }

    SWrapper(std::string name) {
        (*this).name = name;
    }

    bool operator==(SWrapper const& other) {
        return (*this).name == other.name;
    }

    std::string name;
};

class SWrapperHasher {
    size_t operator()(SWrapper const& sw) const {
        return std::hash<std::string>()(sw.name);
    }
};

int main(int argc, char* argv[]) {
    auto mm = std::unordered_multimap<SWrapper, int, SWrapperHasher>();
    return 0;
}

在Arch Linux(或g++ -std=c++11 -Wall -Wpedantic -Wextra hash_map_test.cpp -o hash_map_test)上运行clang++可以正确编译代码。但是,在MacOS上,使用相同的命令,我收到以下错误消息:

In file included from hash_map_test.cpp:1:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/unordered_map:408:
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/__hash_table:868:5: error: 
      static_assert failed due to requirement 'integral_constant<bool, false>::value' "the
      specified hash does not meet the Hash requirements"
    static_assert(__check_hash_requirements<_Key, _Hash>::value,
    ^             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/__hash_table:883:1: note: in
      instantiation of template class
      'std::__1::__enforce_unordered_container_requirements<SWrapper, SWrapperHasher,
      std::__1::equal_to<SWrapper> >' requested here
typename __enforce_unordered_container_requirements<_Key, _Hash, _Equal>::type
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/unordered_map:1682:26: note: while
      substituting explicitly-specified template arguments into function template
      '__diagnose_unordered_container_requirements'
    static_assert(sizeof(__diagnose_unordered_container_requirements<_Key, _Hash, _Pred>(...
                         ^
hash_map_test.cpp:29:15: note: in instantiation of template class
      'std::__1::unordered_multimap<SWrapper, int, SWrapperHasher, std::__1::equal_to<SWrapper>,
      std::__1::allocator<std::__1::pair<const SWrapper, int> > >' requested here
    auto mm = std::unordered_multimap<SWrapper, int, SWrapperHasher>();
              ^
1 error generated.

我已经尝试解释错误消息,但是我真的不知道该怎么做。如果有人对这里发生的事情以及我如何在MacOS上解决此问题提出任何建议,将不胜感激!

c++ stl unordered-map unordered-multimap
1个回答
3
投票

不幸的是,编译器的投诉并未说明未满足哪个要求。在这种情况下,问题出在SWrapperHasher::operator()private。标记public(将class更改为struct会隐式执行此操作)使无序映射合法。

© www.soinside.com 2019 - 2024. All rights reserved.