C ++ method as template argument

I am trying to specialize std :: unordered_map for class X with user hash and user equality. The problem is that both the equality functions and the hashes do not depend only on the object (s) of class X, but also on the data in another (fixed) object of another class Y. Here is an example of a toy (only with a hash function) of what i want to do:

#include <unordered_map>
using namespace std;
struct Y {
  bool b;
  struct X {
    size_t i;
  };
  size_t hash(const X &x) {
    return x.i + b;
  }
  unordered_map<X, int, hash> mymap;
};

The problem is that the hash function in the specialized template is a method, and the compiler complains ("calling a non-static member function without an object argument"). I want y.mymap to use y.hash (). Any way to do this?

Note that in real code, Y is also a template, if that matters.

Thank!

EDIT: , b , X. X, , X , X ( X, ). , , , , .

+4
2

function<size_t(X const&)> , , bind, , :

struct Y {
    bool b;
    struct X {
        size_t i;
        bool operator==(X x) const {return i == x.i;}
    };
    size_t hash(const X &x) {
      return x.i + b;
    }

    struct Hasher {
        Y* this_;
        template <typename T>
        auto operator()(T&& t) const
          -> decltype(this_->hash(std::forward<T>(t))) {
            return    this_->hash(std::forward<T>(t));
        }
    };

    unordered_map<X, int, Hasher> mymap;

    Y() : b(false),
          mymap(0, {this}) {}
};

@dyp, -, this mymap - this_.

Y(Y&& y) : b(y.b), mymap(std::make_move_iterator(std::begin(y.mymap)),
                         std::make_move_iterator(std::end  (y.mymap)), 0, {this}) {}
+2

, , , . . 17.6.3.5/ 26:

h(k) k.

, Y, X.

EDIT: , , b const Y, ( , ):

struct Y
{
    explicit Y(bool config) : b(config), hash_(config), mymap(0, hash_) { }
    const bool b;

    struct X
    {
        size_t i;
    };

    struct Hash
    {
        explicit Hash(bool b) : b_(b) { }
        size_t operator()(const X& x) const
        {
            return x.i + b_;
        }

    private:
        bool b_;
    };

    Hash hash_;
    unordered_map<X, int, Hash> mymap;
};
+2

All Articles