c++ method as template argument -


i trying specialize std::unordered_map class x custom hash , custom equality. problem both equality , hash functions not depend on object(s) of class x on data in (fixed) object of class y. here toy example (with hash function) of want 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 function hash in template specialization method , compiler complains ("call non-static member function without object argument"). want y.mymap uses y.hash(). way this?

note in real code y template, in case matters.

thanks!

edit: clarify, instead of boolean b in code have vector data needed in comparing objects of type x. data added when x created, vector not constant, data given x not change after added, hash given x never changes (so in sense depends on x required hash). main reason use approach save memory since data lot , shared.

you can use function<size_t(x const&)> , e.g. bind, type erasure not necessary in case, here simpler solution:

struct y {     bool b;     struct x {         size_t i;         bool operator==(x x) const {return == 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}) {} }; 

as mentioned @dyp in comments, have careful special member functions since implicitly store this in mymap - i.e. compiler-generated definitions copy this_ pointer. example implementation of move constructor be

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

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -