11/16/2009

11-16-09 - Warning 4244

I wish I could disable warnings about float - double conversions but keep warnings about the conversions between different types of ints. I hate that every time I call sqrt() or whatever in some utility code I have to spend a bunch of time worrying about whether I'm in float or double or whatever, and every time I write FPU utility code I have to write versions for float & double, or cast at the call site, bleck blah lame.

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:

Nicolas said...

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

cbloom said...

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

old rants