For int - int type conversions I'm trying to be good these days and use stuff like these :
// check_value_cast just does a static_cast and makes sure you didn't wreck the value
template < typename t_to, typename t_fm>
t_to check_value_cast( const t_fm & from )
{
t_to to = static_cast< t_to >(from);
RR_ASSERT( static_cast< t_fm >(to) == from );
return to;
}
#define RR_CLAMP_U8(x) (U8)RR_CLAMP(x,0,0xFF)
#define RR_CLAMP_U16(x) (U16)RR_CLAMP(x,0,0xFFFF)
So eg.
S32 val = whatever;
U8 t1 = check_value_cast< U8 >(val); // no clamp but asserts that it fits in range
U8 t2 = RR_CLAMP_U8(val); // clamps to target type range
Losing values to type conversion is one of the few nasty bugs I continue to have, and I'd like it to stop.
2 comments:
I'm pretty much having the same thoughts these days! Just out of curiosity, why do you use a macro + C casts for your clamp code? Did you see performance problems with a templated function?
Cheers,
Nicolas
"Just out of curiosity, why do you use a macro + C casts for your clamp code? Did you see performance problems with a templated function?"
That's a RAD-ism.
At home I use a template for clamp.
Post a Comment