c++ - Is there a difference between `static_cast<bool>(x)` and `x != 0.0`? -
the setup
i'm working api application called motionbuilder. in order access motionbuilder property's value, read double variable, regardless of sort of data type represents.
here's utility function wrote evaluate value of scalar property:
template <typename datat> inline datat getscalar(fbproperty& prop, fbevaluateinfo* evaluateinfo) { double data = 0.0; prop.getdata(&data, sizeof(data), evaluateinfo); return static_cast<datat>(data); }
this way, can write getscalar<float>(camera.roll, evaluateinfo)
or getscalar<bool>(camera.visibility, evaluateinfo)
instead of having multiple-line mess of uninitialized buffers , casts littering code.
i'm compiling in visual studio /w4
, addressing warnings come up. when use getscalar<bool>
, compiler produces a c4800 warning:
'double' : forcing value bool 'true' or 'false' (performance warning)
when compiler creates getscalar<bool>
, winds static_cast double bool, apparently doesn't like. since original aim handle multiple types (bool, float, double, etc) single template function, can't add in usual != 0.0
.
in order address warning, have 2 options.
option 1
i can suppress warning directly pragmas, since cast doing wanted do:
template <typename datat> inline datat getscalar(fbproperty& prop, fbevaluateinfo* evaluateinfo) { double data = 0.0; prop.getdata(&data, sizeof(data), evaluateinfo); #pragma warning (push) #pragma warning (disable: 4800) // don't complain casting bool return static_cast<datat>(data); #pragma warning (pop) }
option 2
i can add specialization of getscalar
handle bool
case:
template <> inline bool getscalar<bool>(fbproperty& prop, fbevaluateinfo* evaluateinfo) { double data = 0.0; prop.getdata(&data, sizeof(data), evaluateinfo); return data != 0.0; }
the question
i think double x, static_cast<bool>(x)
equivalent x != 0.0
. in fact, simple test compiled in release mode gives me same assembly output in both cases. why, then, c4800 call "performance warning?" 2 options outlined above functionally identical? if comes down matter of style, after putting on best pedant hat, option prefer?
it's warning, , it's telling there might performance issue conversion. since want conversion, it. don't waste time writing elaborate workarounds warnings aren't telling useful.
Comments
Post a Comment