我有一个类C,其中有一个私有数据成员string* ps
。
现在,我想要一个unordered_map<C, int>
,为此我需要一个自定义的哈希函数。
根据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
。
我尝试过这个:
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
的情况下解决这种情况?
hash<C>::operator()
的实现中移除template<>
,否则会出现error C2910 cannot be explicitly specialized
。 - Jichaotemplate<>
的情况下,在 Gcc 上,我得到了error: template-id ‘operator()<>’ for ‘std::size_t std::hash<C>::operator()(const C&) const’ does not match any template declaration
。+1 给 Jichao。 - Conchylicultor