Boost logo

Boost :

From: Jonathan Wakely (cow_at_[hidden])
Date: 2005-01-13 13:22:22


On Thu, Jan 13, 2005 at 05:02:33PM +0100, Kristian Dupont wrote:

> 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>

Should that be
    template<class Target, class Source>
because you want Source to be deduced?

jon

> 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

-- 
"Outside of a dog, a man's best friend is a book.  Inside of a dog,
 it's too dark to read."
           -Groucho Marx

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