When I want to convert between different integer types, it seems the best syntax is to use boost::numeric_cast<>()
:
int y = 99999;
short x
You could probably do something like this:
#include
template
Target saturation_cast(Source src) {
try {
return boost::numeric_cast(src);
}
catch (const boost::negative_overflow &e) {
return std::numeric_limits::lowest();
/* Or, before C++11:
if (std::numeric_limits::is_integer)
return std::numeric_limits::min();
else
return -std::numeric_limits::max();
*/
}
catch (const boost::positive_overflow &e) {
return std::numeric_limits::max();
}
}
(For types that support it the error cases could also return -inf/+inf).
This way you let Boost's numeric_cast
determine if the value is out of bounds and can then react accordingly.