简单的 C++11 哈希函数无法编译
Simple C++11 hash function won't compile
以下简单哈希函数的代码无法编译
#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
问题似乎是第一个错误消息中的引用调用,但我不明白为什么或如何解决它。
您缺少一组括号
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()
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 是什么原因导致它无法编译?它是声明签名还是在函数本身的实现中
- C++:编译时检查匹配的函数调用对?
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- C++ 在编译时具有函数计算全局变量
- 在运行时解析函数,而不是在编译C++解析函数
- C++中的双边友语函数:如何使其编译?
- 编译 CUDA 与数学函数的叮当
- CPU_ONLY构建:编译函数 Forward() 会给出错误"undefined reference..."
- 使用额外的模板参数编译函数
- 编译函数时遇到问题
- 注释函数的内容,但保持对函数的调用不变.编译器是否弄清楚不编译函数
- 如何根据模板中的类型编译函数
- XPATHNavigator的编译函数中的"后代"是什么意思?
- 如何为编译时已知的参数的多个值编译函数
- 编译函数模板时出现"expected nested-name-specifier"错误
- 无法编译C++函数
- 防止基于模板参数编译函数(或部分函数)
- 用C++编译函数模板时出错