Whenever boost's numeric_cast<>
conversion fails, it throws an exception. Is there a similar template in boost that lets me specify a default value instead, or is catching the exception the only thing I can do in this case?
I'm not too worried about the performance of all the extra exception handling, but I'd rather use a standard template than write useless wrapper functions. Besides, from past experience, I thought it's likely that boost actually has what I'm thinking of, and I simply haven't found it.
The numeric_cast
function simply calls the boost::numeric::converter
template class with the default arguments. One of the arguments is OverflowHandler
, and the default value for that is def_overflow_handler
, but you can specify silent_overflow_handler
to suppress the exception instead.
Then specify the FloatToIntRounder
argument that will provide your desired default value if the input argument is outside your desired range. The argument is normally used for providing an integer for rounding from a floating-point type, but you can really use it for whatever you want. More information, plus code describing the sequence of events, at the converter
documentation.
As far as I know, Boost doesn't have what you're thinking of, but it provides the facility for you to build it yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With