Hash function for user defined class. How to make friends? :)

前端 未结 2 1900
旧时难觅i
旧时难觅i 2020-12-10 02:58

I have a class C, which has a string* ps private data member.
Now, I\'d like to have an unordered_map for which I need a custom h

相关标签:
2条回答
  • 2020-12-10 03:30

    I'd suggest to add method like following

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

    and use it in the your hash specialization.

    0 讨论(0)
  • 2020-12-10 03:51

    Try this:

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

    Or this:

    class C;
    template<>
    struct std::hash<C>;
    class C{
      friend struct std::hash<C>; // friend the class, not the member function
    };
    

    (I haven't compiled so there might be a syntax error)

    0 讨论(0)
提交回复
热议问题