Mic*_*ice 7 c++ reference hashset c++11
这是有效的C++(考虑到最新标准)吗?我在Ubuntu 12.04上使用near-of-tree-clang/libc ++获得编译错误.如果它应该有效,我将邮件发送给clang-dev列表,其中包含错误消息等.
#include <functional>
#include <unordered_set>
struct X
{
int i;
};
void f ()
{
std::unordered_set<std::reference_wrapper<X>> setOfReferencesToX;
// Do stuff with setOfReferencesToX
}
Run Code Online (Sandbox Code Playgroud)
**顺便说一句,我已经厌倦了这个问题/答案是针对最新标准的.作为一个整体的C++社区,请开始限定旧标准特有的东西吗?新标准已经推出了大约一年了.
问题不是特定的std::reference_wrapper<T>,而是类型X本身.
问题是std :: unordered_set要求您为其定义散列和等式仿函数std::reference_wrapper<X>.您可以将散列函数作为第二个模板参数传递.
例如,这可以工作:
#include <functional> // for std::hash<int>
struct HashX {
size_t operator()(const X& x) const {
return std::hash<int>()(x.i);
}
};
Run Code Online (Sandbox Code Playgroud)
然后
std::unordered_set<std::reference_wrapper<X>, HashX> setOfReferencesToX;
Run Code Online (Sandbox Code Playgroud)
另一个选择是专门化std::hash<X>:
namespace std {
template <>
struct hash<X> {
size_t operator()(const X& x) const {
return std::hash<int>()(x.i);
}
};
}
Run Code Online (Sandbox Code Playgroud)
这允许您避免显式指定第二个模板参数:
std::unordered_set<std::reference_wrapper<X>> setOfReferencesToX;
Run Code Online (Sandbox Code Playgroud)
关于相等比较,您可以通过为类提供相等运算符来解决此问题X:
struct X
{
bool operator==(const X& rhs) const { return i == rhs.i; }
int i;
};
Run Code Online (Sandbox Code Playgroud)
否则,您可以定义自己的仿函数并将其作为第三个模板参数传递.
| 归档时间: |
|
| 查看次数: |
992 次 |
| 最近记录: |