tags:

views:

177

answers:

3

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.

+2  A: 

This has been discussed on the boost mailing list several times, however, no unified solution has been accepted yet. You can use the following placeholder function until then, however, due to exception raising it's neither style nor efficiency-wise nice:

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-made solution would be waaay more efficient.

Kornel Kisielewicz
+4  A: 
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;
}
Roger Pate
+1  A: 

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.

Rob Kennedy