std:hash可以访问类的私有成员

我想散列一个具有两个私有成员的类,例如:

foo.h

class Foo {
    private:
        std::string a;
        std::string b;

    public:
        Foo (std::string a, std::string b);
        bool operator==(const Foo& other) const;
        bool operator!=(const Foo& other) const;
        std::size_t operator()(const Foo& ) const;
};

namespace std {
    template <> struct hash<Foo> {
        std::size_t operator()(const Foo& cp) const;
    };
}

文件

Foo::Foo (std::string _a, std::string _b) {
    this->a = _a;
    this->b = _b;
}

bool Foo::operator== (const Foo& other) const {
    return this->a == other.a && this->b == other.b;
}

bool Foo::operator!= (const Foo& other) const {
    return !operator==(other);
}

std::size_t std::hash<Foo>::operator()(Foo const& foo) const {
    std::string f = foo.a; // << This wont compile!
    return 1;
}

在 C++ 中,Foo当最终的散列函数无法访问 foo 的私有成员时,通常如何进行散列。

随意在您的答案中包含 boost 或 abseil 。

回答

您可以做的是声明std::hash<Foo>为 a friendof Foo

class Foo {
 private:
  std::string a;
  std::string b;

 public:
  Foo(std::string a, std::string b);
  bool operator==(const Foo& other) const;
  bool operator!=(const Foo& other) const;
  std::size_t operator()(const Foo&) const;

  friend std::hash<Foo>;
};


以上是std:hash可以访问类的私有成员的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>