I am sure that there is nothing pre-rolled in the standard and I do not know anything in boost, but it is a large library. Any implementation using casting should be careful with undefined behavior for values ββoutside the range of 4.9 [conv.fpint], but since boost::numeric_cast<> supposedly handles this, you can use:
template <typename U, typename T> inline U is_lossless(T t) { U u = boost::numeric_cast<U>(t); T t2 = boost::numeric_cast<T>(u);
The need for numeric_cast<> when restoring t2 least obvious: it ensures that u is still in range, as this is possible for a value other than say int64_t x to double y for success, but approximate with an integral value in y than outside range for int64_t , so dropping from double has undefined behavior.
The legality / reliability of the above requires that boost::numeric_cast<> correctly avoid undefined behavior that I have not tested yet.
source share