Boost numeric_cast <> with default value instead of exception?

When formatting numeric_cast<> accelerated, numeric_cast<> will throw an exception. Is there a similar pattern in boost that allows me to specify a default value instead, or catch an 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. In addition, from past experience, I thought that most likely boost really has what I think, and I just did not find it.

+4
source share
3 answers

The numeric_cast function simply calls the template class boost::numeric::converter with the default arguments. One argument is OverflowHandler , and the default value for this is def_overflow_handler , but you can specify silent_overflow_handler to throw an exception.

Then specify the FloatToIntRounder argument, which will provide the desired default value if the input argument is outside the desired range. The argument is usually used to provide an integer to round off from a floating point type, but you can really use it for whatever you want. For more information, plus a code that describes the sequence of events in the converter documentation .

As far as I know, Boost does not have what you think, but it provides you with the opportunity to create it yourself.

+6
source
 template<class Target, class Source> typename boost::numeric::converter<Target,Source>::result_type numeric_cast_defaulted(Source arg, Target default_value = Target()) try { return boost::numeric_cast<Target>(Source); } catch (boost::bad_numeric_cast&) { return default_value; } 
+5
source

This has been discussed several times on the mailing list, but a unified decision has not yet been made. You can use the following placeholder function until then, however, due to an exception, without creating either style or efficiency:

 template<typename Target, typename Source> inline Target default_numeric_cast(Source arg, Target def) { try { return numeric_cast<Target,Source>(arg); } catch (...) { return def; } } 

However, a custom solution will be more efficient.

+3
source

All Articles