In order to detect run-time integer casting problems, I've created this function*:
template<typename TTo, typename TFrom>
static inline TTo int_cast(TFrom value)
{
TTo result = static_cast<TTo>(value);
if (static_cast<TFrom>(result) != value || (result >= TTo()) != (value >= TFrom()))
{
throw std::out_of_range("numeric_cast: value out of range");
}
return result;
}
Two questions:
Are there any loopholes in this function I have not accounted for (e.g. undefined behavior)?
What would be the best way to extend this to perform double-to-float and floating-to-integral conversions?
*Note: Yes, I realize Boost has a function like this. But I want my own. :)
int
s? It would be safer and faster. \$\endgroup\$boost::numeric_cast
. \$\endgroup\$