C++ Logo

std-discussion

Advanced search

std::hash (partial) specialization for std::tuple and std::pair?

From: Shachar Shemesh <shachar_at_[hidden]>
Date: Tue, 29 Dec 2020 17:38:14 +0200
Hi all,

I often find is useful to create a hash table (sorry, "unordered_map")
with a key that is either a tuple or a pair. I found it highly
surprising that the default hash implementation does not offer
specialization to those types. This is especially true as writing one
myself did not turn out to be particularly difficult.

static constexpr size_t FibonacciHashMultiplier = 0x9e3779b97f4a7c15;
//static_cast<size_t>(-1) / GoldenRatio;

namespace std {

     template<typename T1, typename T2>
     struct hash< pair<T1, T2> > {
         size_t operator()( const pair<T1, T2> &hashed ) const {
             size_t result = std::hash<T1>()( hashed.first );
             result *= FibonacciHashMultiplier;
             result += std::hash<T2>()( hashed.second );

             return result;
         }
     };
}

I think it is fairly obvious how that above can be extended to handling
std::tuple as well. Is there any reason I'm missing _not_ to include
this in the standard library?

Thanks,
Shachar

Received on 2020-12-29 09:38:26