Standard library implements std::hash as a template struct that is specialized for different types. It is used like this:
#include <iostream>
#include <functional>
int main()
{
std::hash<int> hasher;
std::cout << hasher(1337) << std::endl;
return 0;
}
My question is what is the reasoning behind this design choice. Why it isn't implemented as a template function and used like this:
#include <iostream>
#include <functional>
int main()
{
std::cout << std::hash<int>(1337) << std::endl;
return 0;
}
std::hash<const char*> produces a hash of the value of the pointer (the memory address), it does not examine the contents of any character array.
That means you can only have 256 unique hashes of arbitrary inputs. Since you can definitely create more than 256 different strings, there is no way the hash would be unique for all possible strings.
The answer is no, can't be done for all tuples, since a tuple is a variadic template type.
using c++11, you can: #include <string> #include <unordered_map> std::size_t h1 = std::hash<std::string>{}("MyString"); std::size_t h2 = std::hash<double>{}(3.14159);
There are, multiple reasons, each one good enough to just the choice:
std::hash<T>
being a class template. Note that, partial overloading doesn't help because the hash function would need to be specified somehow as an object which can't be done with overloaded functions (unless they are accessed via an object but that's what is differentiated against).A template function can not be partially specialized for types, while std::hash
specialized for different types as a class template.
And, in this template class based way, you can do some meta programming such as accessing to return type and key type like below:
std::hash<X>::argument_type
std::hash<X>::result_type
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With