Boost logo

Boost :

From: Kristian Dupont (secondary_at_[hidden])
Date: 2005-01-13 11:02:33


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


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