Boost logo

Boost :

Subject: [boost] numeric_cast
From: Brandon Kohn (blkohn_at_[hidden])
Date: 2011-06-16 09:44:06


Hello,

Recently I was creating a new numeric type which I wanted to use along
with boost::numeric_cast. I read over the docs and examples and found
that it seemed to support (at least partially) the notion of policy
driven casting operations. I was unable to figure out how one might use
a custom conversion or overflow policy along with the actual
boost::numeric_cast<N>(x) function. In the end I created a workaround
which seemed to work nicely:

template <typename ConversionTraits, typename EnableIf = void>
struct numeric_cast_traits
{
   typedef def_overflow_handler overflow_handler;
   typedef UseInternalRangeChecker range_checker;
   typedef Trunc
     <
         typename ConversionTraits::source_type
> rounding_policy;
};

template <typename Target, typename Source>
inline Target numeric_cast( Source arg )
{
   typedef boost::numeric::conversion_traits<Target, Source> conv_traits;
   typedef numeric_cast_traits< conv_traits > cast_traits;
   typedef boost::numeric::converter
   <
       Target
     , Source
     , conv_traits
     , typename cast_traits::overflow_handler
     , typename cast_traits::rounding_policy
     , boost::numeric::raw_converter< conv_traits >
     , typename cast_traits::range_checker
> converter;
   return converter()(arg);
}

This change allowed me to easily customize the numeric_cast function for
individual conversion types.

Did I miss something in the official library? If not, would this change
be something good to go in?

Regards,

Brandon Kohn


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk