问题
I'm using std::hash<std::string>()
to create a hash code for a string in C++. The function returns a long double
but I need a uint64_t
for inherited reasons.
Is such a cast safe?
回答1:
C++ Standard paragraph 3.9.1.8 says:
There are three floating point types: float, double, and long double. The type double provides at least as much precision as float, and the type long double provides at least as much precision as double. The set of values of the type float is a subset of the set of values of the type double; the set of values of the type double is a subset of the set of values of the type long double. The value representation of floating-point types is implementation-defined. Integral and floating types are collectively called arithmetic types. Specializations of the standard template std::numeric_limits (18.3) shall specify the maximum and minimum values of each arithmetic type for an implementation.
Which pretty much only says that the long double type should be... longer than the float type.
In practice, long double are usually 80- to 128-bit wide, as explained here: http://en.cppreference.com/w/cpp/language/types
This makes casting (I assume reinterpret_cast) to a uint64_t unsafe, as the some bits from the long double will probably not fit.
回答2:
The std::hash
call operator returns a value of type size_t
that represents the hash value of the parameter.
Thus, the assumption of the question, about long double
return type, seems to be incorrect.
来源:https://stackoverflow.com/questions/21706877/safe-to-cast-long-double-to-uint64-t