0
class pair_hasher { 
    template <class T1, class T2> 
    size_t operator()(const std::pair<T1, T2>& p) const
    { 
        auto hash1 = hash<T1>{}(p.first); 
        auto hash2 = hash<T2>{}(p.second); 
        return hash1 ^ hash2; 
    } 
};

int main() 
{ 
    std::unordered_map<std::pair<int,int>, int, pair_hasher> ht;
    return 0; 
} 

When I compile the above I get

In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/unordered_map:384:
/Library/Developer/CommandLineTools/usr/include/c++/v1/__hash_table:868:5: error: static_assert failed due to requirement
      '__check_hash_requirements<pair<int, int>, pair_hasher>::value'
      "the specified hash does not meet the Hash requirements"
    static_assert(__check_hash_requirements<_Key, _Hash>::value,
    ^             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/usr/include/c++/v1/__hash_table:883:1: note: in instantiation of template class
      'std::__1::__enforce_unordered_container_requirements<std::__1::pair<int, int>, pair_hasher,
      std::__1::equal_to<std::__1::pair<int, int> > >' requested here
typename __enforce_unordered_container_requirements<_Key, _Hash, _Equal>::type
^
/Library/Developer/CommandLineTools/usr/include/c++/v1/unordered_map:828: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>(0)), "");
                         ^
test.cpp:241:52: note: in instantiation of template class 'std::__1::unordered_map<std::__1::pair<int, int>, int,
      pair_hasher, std::__1::equal_to<std::__1::pair<int, int> >, std::__1::allocator<std::__1::pair<const
      std::__1::pair<int, int>, int> > >' requested here
    unordered_map<pair<int,int>, int, pair_hasher> ht;
                                                   ^
1 error generated.

If I change the type of pair_hasher from class to struct, it compiles. Why does class not work here? The compiler error indicates it does not meet the requirements of a hashing function for unordered_map, but it's not clear to me why this is the case.

David
  • 619
  • 2
  • 8
  • 15

0 Answers0