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 = boost::numeric_cast<short>(y); // will throw an exception if y is too large
I have never used that; however the syntax is pretty straightforward, so all is well.
Now suppose I want to do something a bit more advanced: instead of throwing an exception, I’d like it to return the min or max of the target type (saturation). I couldn’t figure out a way to express that, but the documentation suggests that it is possible (probably using RawConverter policy). All I could come up with is the following ugly:
short x = numeric_cast<short>(max(min(y, SHORT_MAX), SHORT_MIN);
So how can I express “saturating cast” using boost’s numeric_cast?
You could probably do something like this:
(For types that support it the error cases could also return -inf/+inf).
This way you let Boost’s
numeric_castdetermine if the value is out of bounds and can then react accordingly.