首页 > 解决方案 > Can I use lambda as a hashing function in boost::multi_index hash-like interface?

问题描述

Is it possible to use lambda for hashing in hashed_<non>_unique interface for boost::multi_index? See this example: https://godbolt.org/z/1voof3

I also saw this: How to use lambda function as hash function in unordered_map? where the answer says:

You need to pass lambda object to unordered_map constructor since lambda types are not default constructible.

and I'm not sure is it even possible to do for the given example on godbolt.

标签: c++boostboost-multi-index

解决方案


Starting with C++20, yes, you can: https://godbolt.org/z/fTbzPP (note f is declared as auto const hash_f, without a &).

As for @sehe's claim that multi_index_containers can't be passed instances of hash objects (or other intervening function objects) at construction time, the claim is incorrect: they can, although the interface is somewhat complicated:

Live Coliru Demo

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <functional>

struct non_default_ctble_hash
{
  non_default_ctble_hash(std::size_t n):n{n}{}
  
  template<typename T>
  std::size_t operator()(const T& x){return std::hash<T>{}(x)*n;}

  std::size_t n;
};

using namespace boost::multi_index;
using container=multi_index_container<
  int,
  indexed_by<
    hashed_unique<identity<int>,non_default_ctble_hash>
  >
>;

int main()
{
  container::ctor_args_list cal{
    {0,identity<int>{},non_default_ctble_hash{666},std::equal_to<int>{}}
  };
  
  container c(cal);
}

推荐阅读