Boost logo

Boost :

From: Fernando Cacciola (fernando_cacciola_at_[hidden])
Date: 2005-01-13 17:53:05


"Kristian Dupont" <secondary_at_[hidden]> escribió en el mensaje
news:cs662h$k8k$1_at_sea.gmane.org...
> Forgive me if this topic has been discussed before - searching for "casts"
> and the like in the archives bring out quite a lot of results :)
>
> Although numeric_cast allows you to safely cast between numeric types, I
> find that it can sometimes come in handy to just receive the saturated
> value
> in the case of an overflow. A simplified solution would look something
> like
> this:
>
> template<class Source, class Target>
> inline Target saturated_cast(Source val)
> {
> BOOST_STATIC_ASSERT(std::numeric_limits<Target>::is_specialized);
>
> if(val < (std::numeric_limits<Target>::min)())
> return (std::numeric_limits<Target>::min)();
>
> if(val > (std::numeric_limits<Target>::max)())
> return (std::numeric_limits<Target>::max)();
>
> return static_cast<Target>(val);
> }
>
> I think that this would fit nicely into cast.hpp. Any comments?
>
> Kristian Dupont
>

Please, take a look at the new Boost Numeric Conversion Library:

http://www.boost.org/libs/numeric/conversion/doc/index.html

It replaces numeric_cast<> in cast.hpp (except for BCB and VC6 for which the
new code has not been ported yet)

Altough what you suggested is not supported by the new code, it would be
easy to add a policy to select this saturating behaviour.. I used it in the
past and I know that in certain contexts is very useful.

Before doing it, however, I would like to see if there's a broader scope in
which this particular change fit; that is, to see a bigger picture, if any.

Best,

Fernando Cacciola


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