Can I override std::hash?

10.8k views Asked by At

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 ?

2

There are 2 answers

5
Some programmer dude On BEST ANSWER

Yes it's okay, and you don't have to modify the standard library in any way, just use template specialization:

namespace std
{
    template<>
    struct hash<YourSpecialType>
    {
        // ...
    };
}
3
doctorlove On

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