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_castfunction simply calls theboost::numeric::convertertemplate class with the default arguments. One of the arguments isOverflowHandler, and the default value for that isdef_overflow_handler, but you can specifysilent_overflow_handlerto suppress the exception instead.Then specify the
FloatToIntRounderargument 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 theconverterdocumentation.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.