Skip to content

Instantly share code, notes, and snippets.

@607011
Created December 15, 2023 16:07
Show Gist options
  • Save 607011/e241f9f71728c87cc13611cf3b01ca0c to your computer and use it in GitHub Desktop.
Save 607011/e241f9f71728c87cc13611cf3b01ca0c to your computer and use it in GitHub Desktop.
std::tuple hasher
#ifndef __TUPLE_HASHER_HPP__
#define __TUPLE_HASHER_HPP__
#include <tuple>
#include <functional>
template <class T>
inline void hash_combine(std::size_t &seed, T const &v)
{
seed ^= std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
// Recursive template code derived from Matthieu M.
template <class Tuple, size_t Index = std::tuple_size<Tuple>::value - 1>
struct HashValueImpl
{
static void apply(size_t &seed, Tuple const &tuple)
{
HashValueImpl<Tuple, Index - 1>::apply(seed, tuple);
hash_combine(seed, get<Index>(tuple));
}
};
template <class Tuple>
struct HashValueImpl<Tuple, 0>
{
static void apply(size_t &seed, Tuple const &tuple)
{
hash_combine(seed, get<0>(tuple));
}
};
template <typename... TT>
struct std::hash<std::tuple<TT...>>
{
size_t
operator()(std::tuple<TT...> const &tt) const
{
size_t seed = 0;
HashValueImpl<std::tuple<TT...>>::apply(seed, tt);
return seed;
}
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment