Can I override std :: hash?

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

I mean my code base without touching the standard library.

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

+4
source share
2 answers

Yes, everything is in order, and you do not need to modify the standard library in any way, just use a specialized specialization:

 namespace std { template<> struct hash<YourSpecialType> { // ... }; } 
+3
source

You can specialize a hash for certain types. See here and here , for example. like this

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

If you think you can do better than library developers for existing versions, you are either 1. incorrect or 2. smart

+6
source

Source: https://habr.com/ru/post/1495515/


All Articles