I am doing a bunch of applied-mathematics/signal-processing/algorithms C++ code.
I have enabled the -Wconversion
compiler warning to catch issues like runtime conversion of numbers that are type double
to type int32_t
.
Obviously I am always concerned during these conversions because:
- loss of the numbers decimal value
- possible positive or negative overflow ("positive overflow" is when a double has a value greater than
INT32_MAX
and tries to store that value in the destination type (int32_t
in this case))
Whenever I am concerned about such a conversion I usually use the one-liner check:
boost::numeric_cast<DestType>(SourceType)
However I would like to do the same thing without boost
.
Does straight C++ have an equivalent to boost::numeric_cast<DestType>(SourceType)
?
If straight C++ does not have an equivalent, what would be a comparable non-boost
implementation?
I would think a somewhat comparable check would be basically a template function that has a single if statement to check the input parameter against positive or negative overflow (by using the std::numeric_limits<DestType>
::max()
and ::min()
and throws an exception).