这在任何地方都是“标准化的”吗?
如果你指的是哈希算法,那么(就像很多事情一样)已经有一个完整的解决方案boost
.
boost
is of course, arguably more standardised and certainly more portable than the various implementations of the c++ standard itself.1
#include <boost/functional/hash.hpp>
#include <tuple>
#include <utility>
#include <array>
#include <string>
#include <iostream>
template<class T>
std::size_t hashit(T const& x)
{
using x_type = std::decay_t<T>;
return boost::hash<x_type>()(x);
}
template<class T>
std::size_t hashit2(T const& x)
{
using boost::hash_value;
return hash_value(x);
}
int main()
{
using namespace std::literals;
std::cout << hashit(std::make_tuple(1, 2, 5, "foo"s)) << '\n';
std::cout << hashit2(std::make_tuple(1, 2, 5, "foo"s)) << '\n';
std::cout << '\n';
std::cout << hashit(std::make_pair(1.0, 2.0)) << '\n';
std::cout << hashit2(std::make_pair(1.0, 2.0)) << '\n';
std::cout << '\n';
std::cout << hashit(std::array<int, 3>{4, 5, 6}) << '\n';
std::cout << hashit2(std::array<int, 3>{4, 5, 6}) << '\n';
}
1 This will be seen by many as a controversial statement. It is nonetheless empirically true.