【问题标题】:Hash function for user defined class. How to make friends? :)用户定义类的哈希函数。如何交朋友? :)
【发布时间】: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&lt;C&gt; 就无法知道ps

我在这里做错了什么?在不公开ps 的情况下如何解决这种情况?

【问题讨论】:

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


    【解决方案1】:

    试试这个:

    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
    };
    

    (我没有编译所以可能有语法错误)

    【讨论】:

    • 是的,没错,谢谢,我会在几秒钟内将其标记为接受。与此同时,我也发现自己有多傻! [尴尬]:)
    • 对于 msvc2012,您需要在 size_t 的实现中删除 template&lt;&gt; hash&lt;C&gt;::operator(),否则 error C2910 cannot be explicitly specialized
    • +1 为极超。在 Gcc 上不删除 template&lt;&gt;,我得到 error: template-id ‘operator()&lt;&gt;’ for ‘std::size_t std::hash&lt;C&gt;::operator()(const C&amp;) const’ does not match any template declaration
    【解决方案2】:

    我建议添加如下方法

    class C
    {
    ....
    public:  const string* get_ps() const { return ps; }
    ....
    };
    

    并在您的哈希专业化中使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-25
      • 2012-05-15
      • 1970-01-01
      • 2011-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      相关资源
      最近更新 更多