在 MacOS 上为 unordered_multimap 中的自定义类型定义哈希函数时遇到问题

Trouble definining hash function for custom type in unordered_multimap on MacOS

所以我想使用自定义类型(此处为 SWrapper)作为 unordered_multimap 的键类型。我已经定义了一个散列 class,派生自字符串的标准散列函数,并将散列 class 包含在多重映射的类型中。下面显示了一些重现错误的代码。这在 Arch Linux 上用 g++ 和 clang++ 编译,但在 MacOS 上用 clang++ 编译,我得到错误:

#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;
}

运行 g++ -std=c++11 -Wall -Wpedantic -Wextra hash_map_test.cpp -o hash_map_test 在 Arch Linux(或 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 上解决这个问题有任何建议,我们将不胜感激!

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