用户定义类的哈希函数。如何交朋友? :) [英] Hash function for user defined class. How to make friends? :)
问题描述
我有一个类C,它有一个 string * ps
私人数据成员。
现在,我想有一个 unordered_map< C,int>
为我需要一个自定义哈希函数。
I have a class C, which has a string* ps
private data member.
Now, I'd like to have an unordered_map<C, int>
for which I need a custom hash function.
根据c ++引用,我可以这样做
namespace std {
template<>
class hash<C> {
public:
size_t operator()(const C &c) const
{
return std::hash<std::string>()(*c.ps);
}
};
}
问题是我似乎不能使 operator()
和 C
朋友,以便我可以访问 ps
。
The problem is that I can't seem to make operator()
and C
friends so that I could access ps
.
我尝试过:
class C;
template<>
class std::hash<C>;
class C{
//...
friend std::hash<C>::operator ()(const C&) const; // error: Incomplete type
};
// define hash<C> here.
但它表示不完整类型...在嵌套名称说明符...
but it says that Incomplete type ... in nested name specifier ...
我也不能翻转这些定义,因为如果C类稍后定义, hash< C>
知道 ps
。
I can't turn around the definitions either, because if class C is defined later, the hash<C>
has no way to know about ps
.
我在这里做错了什么?
What am I doing wrong here? How can this situation be fixed without making ps
public?
推荐答案
如何解决这个问题?这个:
Try this:
class C;
namespace std {
template<>
class hash<C> {
public:
size_t operator()(const C &c) const; // don't define yet
};
}
class C{
//...
friend std::hash<C>::operator ()(const C&) const;
};
namespace std {
template<>
size_t hash<C>::operator()(const C &c) const {
return std::hash<std::string>()(*c.ps);
}
}
或:
class C;
template<>
class std::hash<C>;
class C{
friend class std::hash<C>; // friend the class, not the member function
};
(我没有编译,所以可能会出现语法错误)
(I haven't compiled so there might be a syntax error)
这篇关于用户定义类的哈希函数。如何交朋友? :)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!