【发布时间】:2012-12-03 04:00:18
【问题描述】:
我有一个 C 类,它有一个 string* ps 私有数据成员。
现在,我想要一个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 朋友,以便我可以访问 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 的情况下如何解决这种情况?
【问题讨论】:
标签: c++ hash c++11 unordered-map