8

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 ?

Marc Mutz - mmutz
  • 24,485
  • 12
  • 80
  • 90
user2485710
  • 9,451
  • 13
  • 58
  • 102
  • 1
    You can provide a specialization for *your* own types. – Xeo Aug 06 '13 at 11:32
  • @Xeo yes, I know that, but I was interested in a global change. – user2485710 Aug 06 '13 at 11:35
  • Possible duplicate of [How to specialize std::hash::operator() for user-defined type in unordered containers?](https://stackoverflow.com/questions/8157937/how-to-specialize-stdhashkeyoperator-for-user-defined-type-in-unordered) – M.J. Rayburn Sep 01 '17 at 20:28

2 Answers2

9

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

Community
  • 1
  • 1
doctorlove
  • 18,872
  • 2
  • 46
  • 62
  • 1
    _3. lazy_ , so I can get a new hash function without writing X new types. – user2485710 Aug 06 '13 at 11:35
  • "X new types"? Just write a myHash function and use that instead, but that's probably not lazy - you will have to read Knuth for hours first to get it right. – doctorlove Aug 06 '13 at 11:37
  • the lazy part was about "writing" indeed :D but thanks for the reference to the creator of Tex and other bozillion of algorithms and books. – user2485710 Aug 06 '13 at 11:38
7

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>
    {
        // ...
    };
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621