c++ - 用户定义类的哈希函数。如何交 friend ? :)

标签 c++ hash c++11 unordered-map

我有一个 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/

相关文章:

C++构造函数性能

c++ - 如何使用 boost 日志防止内存增长?

java - Eclipse生成的hashCode函数好用吗?

c++ - 根据形参函数实参类型重载函数模板

c++ - 为什么编译器不警告无符号到有符号的转换?

c++ - 处理派生类指针 vector 的正确方法?

C++ 在类中设置迭代器

c++ - 循环中的(非)静态对象

hash - 双向哈希算法?

php - 将 md5 密码哈希值转换为 PHP 5.5 password_hash()