I am looking for a Standard Library or Boost function that can losslessly cast a number to another primitive type and somehow inform me whether the cast was lossless (or throw an exception if it is not). Here are some examples:
auto x = lossless_cast<double>(1u); // ok, double can represent 1
auto x = lossless_cast<int>(1.2); // fail, int can't represent 1.2
auto x = lossless_cast<int>(1E200); // fail, int can't represent 1E200
boost::numeric_cast
comes close in that it will pick up casts that fall out of the numeric range of the target type, but not if they are lossless but within the target type (see my 2nd example).
There is a SO question for the C language which provides some hand-rolled solutions to this problem, but I am after a boost
or Standard Library solution, basically with the following functionality:
template <typename out, typename in>
out lossless_cast(in in_value)
{
out out_value = static_cast<out>(in_value);
if (static_cast<in>(out_value) != in_value)
throw; // some exception
return out_value;
}
Does this functionality exist?