用户定义类的哈希函数.如何交朋友?:).
Hash function for user defined class. How to make friends? :)
我有一个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
?
试试这个:
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
};
(我还没有编译,所以可能有语法错误)
更简单的交友方式:
class C {
template <typename T> friend class std::hash;
};
即使 C 位于自己的命名空间中或是一个嵌套类,这也有效,因为 std::hash 不必向前声明。
我建议添加如下方法
class C
{
....
public: const string* get_ps() const { return ps; }
....
};
并将其用于哈希专用化。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 如何与基类中的派生类函数交朋友
- 用户定义类的哈希函数.如何交朋友?:).
- 类无法与不在其命名空间中的函数交朋友
- 试图与 Base 中的派生函数交朋友 - 为什么它不起作用?