| 1 | #ifndef INCLUDED_PVPGN_HASH_TUPLE_H |
| 2 | #define INCLUDED_PVPGN_HASH_TUPLE_H |
| 3 | |
| 4 | #include <cstddef> |
| 5 | #include <functional> |
| 6 | #include <tuple> |
| 7 | |
| 8 | // https://stackoverflow.com/questions/7110301/generic-hash-for-tuples-in-unordered-map-unordered-set |
| 9 | namespace pvpgn |
| 10 | { |
| 11 | namespace hash_tuple |
| 12 | { |
| 13 | template <typename TT> |
| 14 | struct hash |
| 15 | { |
| 16 | std::size_t operator()(TT const& tt) const |
| 17 | { |
| 18 | return std::hash<TT>()(tt); |
| 19 | } |
| 20 | }; |
| 21 | |
| 22 | namespace |
| 23 | { |
| 24 | template <class T> |
| 25 | inline void hash_combine(std::size_t& seed, T const& v) |
| 26 | { |
| 27 | seed ^= hash_tuple::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | namespace |
| 32 | { |
| 33 | // Recursive template code derived from Matthieu M. |
| 34 | template <class Tuple, std::size_t Index = std::tuple_size<Tuple>::value - 1> |
| 35 | struct HashValueImpl |
| 36 | { |
| 37 | static void apply(std::size_t& seed, Tuple const& tuple) |
| 38 | { |
| 39 | HashValueImpl<Tuple, Index - 1>::apply(seed, tuple); |
| 40 | hash_combine(seed, std::get<Index>(tuple)); |
| 41 | } |
| 42 | }; |
| 43 | |
| 44 | template <class Tuple> |
| 45 | struct HashValueImpl<Tuple, 0> |
| 46 | { |
| 47 | static void apply(std::size_t& seed, Tuple const& tuple) |
| 48 | { |
| 49 | hash_combine(seed, std::get<0>(tuple)); |
| 50 | } |
| 51 | }; |
| 52 | } |
| 53 | |
| 54 | template <typename ... TT> |
| 55 | struct hash<std::tuple<TT...>> |
| 56 | { |
| 57 | std::size_t operator()(std::tuple<TT...> const& tt) const |
| 58 | { |
| 59 | std::size_t seed = 0; |
| 60 | HashValueImpl<std::tuple<TT...> >::apply(seed, tt); |
| 61 | return seed; |
| 62 | } |
| 63 | }; |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | #endif |