我有一个 C 类,它有一个 string* ps
私有(private)数据成员。
现在,我想要一个 unordered_map<C, int>
我需要一个自定义哈希函数。
According to the c++ reference , 我可以这样做
namespace std {
template<>
class hash<C> {
public:
size_t operator()(const C &c) const
{
return std::hash<std::string>()(*c.ps);
}
};
}
问题是我似乎无法制作 operator()
和 C
friend ,以便我可以访问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.
但它说不完整类型...在嵌套名称说明符中...
我也无法改变定义,因为如果稍后定义 C 类,hash<C>
无从得知ps
.
我在这里做错了什么?不制作 ps
如何解决这种情况公开?
最佳答案
试试这个:
class C;
namespace std {
template<>
struct hash<C> {
public:
size_t operator()(const C &c) const; // don't define yet
};
}
class C{
//...
friend size_t 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<>
struct std::hash<C>;
class C{
friend struct std::hash<C>; // friend the class, not the member function
};
(我没有编译所以可能有语法错误)
关于c++ - 用户定义类的哈希函数。如何交 friend ? :),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13890747/