How to specialize std :: hash for a type from another library

So, the library that I use has an enumeration (let's say it's called LibEnum ). I need to have std::unordered_set from LibEnum , but I get a compilation error that there is no specialized std::hash . I could easily write it and simply return the number of values ​​(the first element is 0, the second 1, etc.), But where exactly should I put this specialization and what should it look like? I cannot change library sources.

  enum LibEnum { A, B, C, D}; std::unordered_set <LibEnum> mySet; //need std::hash for LibEnum //how should it look like? 
+1
c ++ stl hash unordered-set stdhash
Feb 11 '13 at 14:23
source share
1 answer

You can just specialize std::hash for your type:

 namespace std { template <> struct hash<FullyQualified::LibEnum> { size_t operator ()(FullyQualified::LibEnum value) const { return static_cast<size_t>(value); } }; } 

Alternatively, you can define the hash type, wherever you are, and simply provide it as an optional template argument when creating an instance of std::unordered_map<FooEnum> :

 // Anywhere in your code prior to usage: struct myhash { std::size_t operator ()(LibEnum value) const { return static_cast<std::size_t>(value); } }; // Usage: std::unordered_map<LibEnum, T, myhash> some_hash; 

None of the methods require changing the library.

+8
Feb 11 '13 at 14:27
source share



All Articles