samedi 26 septembre 2015

How to override std::hash for an enum defined inside a class?

I've got an enumeration type defined inside of a class, and I want to create an unordered_set of those objects as a member of the class:

#include <unordered_set>

class Foo {
public:
  enum Bar {
    SOME_VALUE
  };

  // Error: implicit instantiation of std::hash
  std::unordered_set<Bar> getValues() const {
     return _values;
  }

private:
  std::unordered_set<Bar> _values;
};

Now, I know the obvious answer is to add a custom hash function to the unordered_set:

std::unordered_set<Bar, BarHasher>

However, what I'm wondering is if there's a way to specialize std::hash for the Bar enum so that anyone who uses unordered_map gets the hashing behavior automatically.

This works with every other data type, but not enums - because enums cannot be forward declared.

In order for this to work, I'd have to put the definition of std::hash after the enum definition, but before the first use, which means I'd have to put it in the middle of the class body, which won't work.

Aucun commentaire:

Enregistrer un commentaire