Chris Chris - 1 year ago 88
C++ Question

Type conversions without loss of precision

I've just recently noticed some of the code in the framework I am working with converts certain variables to doubles and then back when they are accessed by the framework. In the C++11 standard, is this guaranteed to work without loss of precision for any integral types? If so, which? Are there any additional types that are universally safe for this kind of conversion in common implementations?

Also, is there any way to check at compile time that a conversion is safe in this way? Essentially I would like something like:

static_assert(T(double(T type))==type);

Answer Source

T(double(T_value))==T_value is guaranteed when the range of integral type T is a subrange of the range of exact integral values of type double.

Since no implementation of double has 16 bits or less for the mantissa, and since as far as I know there's no extant C++ implementation with more than 16 bits per byte (the CHAR_BIT constant from <limits.h>), this guarantee holds for char and and the explicitly signed and unsigned variants.

Typically a double has some 50+ bits mantissa, and that's enough for the guarantee to hold also for 32-bit integral types, but not for 64-bit.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download