0

所以我想使用自定义类型(此处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;
}

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 上解决此问题有任何建议,我们将不胜感激!

4

1 回答 1

3

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

于 2020-04-03T00:34:28.823 回答