c++ - std:hash 可以访问类的私有成员
问题描述
我想散列一个有两个私有成员的类,例如:
foo.h
class Foo {
private:
std::string a;
std::string b;
public:
Foo (std::string a, std::string b);
bool operator==(const Foo& other) const;
bool operator!=(const Foo& other) const;
std::size_t operator()(const Foo& ) const;
};
namespace std {
template <> struct hash<Foo> {
std::size_t operator()(const Foo& cp) const;
};
}
foo.cpp
Foo::Foo (std::string _a, std::string _b) {
this->a = _a;
this->b = _b;
}
bool Foo::operator== (const Foo& other) const {
return this->a == other.a && this->b == other.b;
}
bool Foo::operator!= (const Foo& other) const {
return !operator==(other);
}
std::size_t std::hash<Foo>::operator()(Foo const& foo) const {
std::string f = foo.a; // << This wont compile!
return 1;
}
在 C++ 中,Foo
当最终哈希函数无法访问 foo 的私有成员时,通常如何进行哈希处理。
随意在您的答案中加入 boost 或 abseil。
解决方案
您可以做的是声明std::hash<Foo>
为friend
of Foo
:
class Foo {
private:
std::string a;
std::string b;
public:
Foo(std::string a, std::string b);
bool operator==(const Foo& other) const;
bool operator!=(const Foo& other) const;
std::size_t operator()(const Foo&) const;
friend std::hash<Foo>;
};
推荐阅读
- system.io.pipelines - 只读序列
从 ReadOnlySequence 转换 ? - java - 在集成测试 RestController 时禁用或模拟 Spring Security 过滤器
- javascript - 单击复选框时,将其值添加到文本框值
- superset - 在 Apache Superset 3.7 中无法访问 ResetMyPassword
- r - par 函数,如何为多个图设置适当的值?
- azure - azure cloud powershell runbook 在存储帐户中上传
- angular - 错误 TS2345:类型参数 '{ headers: HttpHeaders; }' 不可分配给“RequestOptionsArgs”类型的参数
- r - r:选择年份最高的行,然后是最高月份
- javascript - 在 iOS 中使用 React Native 的 Google 地图
- android - whatsapp、messenger 和其他非常著名的消息应用程序如何在应用程序被杀死时接收推送通知?