简单的C ++ 11哈希函数无法编译

时间:2019-06-06 18:23:35

标签: c++ c++11 hash

以下用于简单哈希函数的代码无法编译

#include <cstddef>
#include <functional>

namespace {
    struct Foo {
        long i;
    };
}

namespace std {
    template<> struct hash<::Foo> {
        size_t operator()(::Foo foo) const {
            return hash<decltype(foo.i)>(foo.i);
        }
    };
}

我的4.8.5 g ++编译器发出以下消息:

$ g++ -std=c++11 a.cpp
a.cpp: In member function ‘std::size_t std::hash<{anonymous}::Foo>::operator()({anonymous}::Foo) const’:
a.cpp:13:47: error: no matching function for call to ‘std::hash<long int>::hash(long int&)’
             return hash<decltype(foo.i)>(foo.i);
                                               ^
a.cpp:13:47: note: candidates are:
In file included from /usr/include/c++/4.8.2/bits/basic_string.h:3033:0,
                 from /usr/include/c++/4.8.2/string:52,
                 from /usr/include/c++/4.8.2/stdexcept:39,
                 from /usr/include/c++/4.8.2/array:38,
                 from /usr/include/c++/4.8.2/tuple:39,
                 from /usr/include/c++/4.8.2/functional:55,
                 from a.cpp:2:
/usr/include/c++/4.8.2/bits/functional_hash.h:107:3: note: constexpr std::hash<long int>::hash()
   _Cxx_hashtable_define_trivial_hash(long)
   ^
/usr/include/c++/4.8.2/bits/functional_hash.h:107:3: note:   candidate expects 0 arguments, 1 provided
/usr/include/c++/4.8.2/bits/functional_hash.h:107:3: note: constexpr std::hash<long int>::hash(const std::hash<long int>&)
/usr/include/c++/4.8.2/bits/functional_hash.h:107:3: note:   no known conversion for argument 1 from ‘long int’ to ‘const std::hash<long int>&’
/usr/include/c++/4.8.2/bits/functional_hash.h:107:3: note: constexpr std::hash<long int>::hash(std::hash<long int>&&)
/usr/include/c++/4.8.2/bits/functional_hash.h:107:3: note:   no known conversion for argument 1 from ‘long int’ to ‘std::hash<long int>&&’
$ fg

问题似乎是第一个错误消息中的引用调用,但我不知道为什么或如何解决。

1 个答案:

答案 0 :(得分:5)

您缺少其中的一组括号

return hash<decltype(foo.i)>(foo.i);

在上面,您尝试构造一个std::hash,而不是调用它的operator()。您需要

return hash<decltype(foo.i)>()(foo.i);
// or
return hash<decltype(foo.i)>{}(foo.i);

其中一组空的括号/大括号构造了哈希对象,第二组调用了其operator()