Reputation: 667
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
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