Can I override std::hash?

user2485710 picture user2485710 · Aug 6, 2013 · Viewed 7k times · Source

I can replace the actual implementation of std::hash with my own definition of std::hash in C++ 11 ?

I mean from my codebase, without touching the standard library.

I can't see any use for virtual function/polymorphism in this case, so I suppose that I can't alter the definition of std::hash anyway ?

Answer

doctorlove picture doctorlove · Aug 6, 2013

You can specialise hash for specific types. See here and here e.g. like this

namespace std {
  template <> struct hash<Foo>
  {
    size_t operator()(const Foo & x) const
    {
      /* your code here, e.g. "return hash<int>()(x.value);" */
    }
  };
}

If you think you can do better than the library implementors for existing versions you are either 1. wrong or 2. clever