Is there a purpose to using boost::numeric_cast<double>(long) (i.e., converting from long to double)?

Viewed 102

I thought that this conversion cannot fail. So boost::numeric_cast<double>(long) should produce the same result as just a regular cast. Is this correct? If so, why is the boost::numeric_cast slower than a regular cast? Is there some sort of check it is doing?

2 Answers

From the documentation:

The lack of preservation of range makes conversions between numeric types error prone. This is true for both implicit conversions and explicit conversions (through static_cast). numeric_cast detects loss of range when a numeric type is converted, and throws an exception if the range cannot be preserved.

So it looks like boost's numeric casts do some extra checking, and can throw exceptions -- so they're not always the same as a "regular cast".

static_assert((1ull<<57ull)!=(1+(1ull<<57ull)));
static_assert((double)(1ull<<57ull)==(double)(1+(1ull<<57ull)));

boost numeric cast would throw rather that round, as the above code does.

64 bit integers can represent some integers that 64 bit doubles cannot. 64 bit doubles spend bits on the 'exponent'.

Related