Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost numeric_cast<> with a default value instead of an exception?

Tags:

c++

boost

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.

like image 398
Roman Starkov Avatar asked Dec 10 '22 18:12

Roman Starkov


1 Answers

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.

like image 57
Rob Kennedy Avatar answered Mar 29 '23 23:03

Rob Kennedy