1
#include <variant>
#include <unordered_map>

struct Foo {int a, b;};
struct Bar {};
struct Baz {};

auto main() -> int {
  const std::unordered_map<std::variant<Foo, Bar, Baz>, int> hello = {
    {Foo{1, 2}, 1}
  };
  return 0;
}

Clang complains of:

error: static_assert failed due to requirement '__is_invocable<const std::hash<std::variant<Foo, Bar, Baz> > &, const std::variant<Foo, Bar, Baz>&>{}' "hash function must be invocable with an argument of key type"`

and numerous other errors.

We can already use variants in unordered_map like so:

const std::unordered_map<std::variant<std::string, int>, int> a = {
  {"This is a test", 1},
  {200, 2}
};

Is there a way to use constructors of bare-bone structs as keys in this way?

  • This has nothing to do with `std::variant`. `unordered_map` needs to know how to hash its key type as well as compare it for equality. – Praetorian Oct 02 '18 at 04:30
  • 1
    From [cppreference](https://en.cppreference.com/w/cpp/utility/variant/hash): "The specialization `std::hash>` is enabled ... if every specialization in `std::hash>...` is enabled, and is disabled otherwise." You'll need to roll your own hash function, either one for the whole variant or one for every type in the variant. See an example [here](https://en.cppreference.com/w/cpp/utility/hash) of how to specialize `std::hash` – alter_igel Oct 02 '18 at 04:30

0 Answers0