[英]Specializing std::hash for private member class
I have a class (call it Outer
) which has a private member class ( Inner
). 我有一个类(称为
Outer
),它有一个私有成员类( Inner
)。 I want to store instances of Outer::Inner
in unordered standard containers, so I want to specialize std::hash<Outer::Inner>
. 我想在无序的标准容器中存储
Outer::Inner
实例,所以我想专门化std::hash<Outer::Inner>
。
However, when writing this: 但是,写这篇文章的时候:
namespace std {
template<>
struct hash<Outer::Inner> {
std::size_t operator()(const Outer::Inner &arg) const
{
return std::hash<int>()(arg.someSpecialProperty);
}
};
}
the compiler complains: 编译器抱怨:
error: 'Inner' is a private member of 'Outer'
std::size_t operator()(const Outer::Inner &p) const
^
I have tried to make std::hash
a friend struct by following this answer , but that didn't work either: the forward declaration of Outer::Inner
failed with: 我试图通过遵循这个答案使
std::hash
成为朋友结构,但这也不起作用: Outer::Inner
的前向声明失败了:
error: use of undeclared identifier 'Outer'
So how should I proceed (if what I intend to do is possible at all)? 那我该怎么办(如果我打算做的话可能的话)?
Got it ! 得到它了 ! The solution is to use your own functors, not specialize std::hash.
解决方案是使用您自己的仿函数,而不是专门的std :: hash。
struct A
{
A() { v.insert(std::make_pair(B(1), 6)); }
private:
struct B
{
B(int i = 0) : m_i(i) { }
int m_i;
};
struct HashB { std::size_t operator()(const B& b) const { return b.m_i; } };
struct EqualB { bool operator()(const B&b1, const B&b2) const { return b1.m_i == b2.m_i; } };
std::unordered_map<B, int, HashB, EqualB> v;
};
Since it's a private inner type, I assume that you have a private
or protected
std::unordered_map
member in the enclosing class. 由于它是一个私有内部类型,我假设你在封闭类中有一个
private
或protected
std::unordered_map
成员。 If that's the case, just write a private inner hash functor and pass it as the third argument of the std::unordered_map
. 如果是这种情况,只需编写一个私有内部哈希函子并将其作为
std::unordered_map
的第三个参数传递。 It's the easiest solution to your problem, I think. 我认为这是解决问题的最简单方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.