A common theme among the other answers is the concern about whether or not you can assume that the doubles are implemented via IEEE 754 or not.
I'd argue that for many purposes your original method is best: cast the given int64_t to a double, then assign the result back to a second int64_t, and compare the two.
Regarding your concern about excess precision, that shouldn't be applicable as long as you know that the value has actually been written to memory and read back, because at that stage there shouldn't be any way for the compiler to store the "excess precision" for that variable. Based on the answers at your original link, I believe the following example would be enough to force that behavior:
bool losslessRoundTrip(int64_t valueToTest)
{
double newRepresentation;
*((volatile double *)&newRepresentation) = static_cast<double>(valueToTest);
int64_t roundTripValue = static_cast<int64_t>(newRepresentation);
return roundTripValue == valueToTest;
}
I suspect that simply declaring newRepresentation as volatile would be enough, but I don't use the volatile keyword enough to be sure, so I've simply adapted the solution from your link.
The nice thing about your original method is that it should work for pretty much anything supporting the right casts and operators, as long as you only care about whether you can come back to the initial type like this. For example, here is a generic implementation:
template<typename T1, typename T2>
bool losslessRoundTrip(T1 valueToTest)
{
T2 newRepresentation;
*((volatile T2 *)&newRepresentation) = static_cast<T2>(valueToTest);
T1 roundTripValue = static_cast<T1>(newRepresentation);
return roundTripValue == valueToTest;
}
Please note that this might not be the best answer for your question, because it still seems a cheat to check whether you can store it as a double by...storing it as a double. Still, I don't know how else to avoid relying on mechanics of the internal representation.
It also doesn't quite check whether it was losslessly stored in the double, but rather whether the round-trip from int64_t to double, and back to an int64_t is lossless on that platform. I don't know whether it's possible for there to be casting errors that cancel out when casts are applied in both directions (I'll appeal to someone with more knowledge for that), but in my opinion, I usually consider it close enough to "lossless" if I can get the initial value back if I convert back to the same type.