theotherphil
theotherphil

Reputation: 667

How do I safely cast between any numeric types with clipping if required?

I'd like a function of the following form

template <typename T, typename U>
U clipAndCast(T x)
{
  ... 
  return y;  
 }, 

where y is x cast to type U, but with x clipped if required so that this cast is well-defined.

Is there a library or boost function do to this? I can't find one, so if not what's the best way to write such a function?

Upvotes: 0

Views: 131

Answers (2)

wilx
wilx

Reputation: 18228

Take a look at Boost's Numerical Conversions library.

Upvotes: 1

Pete Becker
Pete Becker

Reputation: 76325

The way to do it is to test whether the value coming in is greater than or equal to the minimum value of the type going out and less than or equal to the maximum value of the type going out. You can use std::numeric_limits<U>::min() and std::numeric_limits<U>::max() to get the minimum and maximum values.

Upvotes: 1

Related Questions