On 22/11/2018 19:08, Emil Dotchevski wrote:
On Wed, Nov 21, 2018 at 7:43 PM Gavin Lambert wrote:
Where implicit conversions are permitted, there is no difference in actual compiled behaviour at the call site between an implicit and explicit conversion. At all. They are utterly identical.
Nope, they're different. Implicit conversions convert to the target type, while a static_cast converts to what you tell it to convert. Consider:
void f(long); void f(short); void f(double); ....
f(x);
Is semantically different from
f( static_cast<short>(x) );
Things get even more interesting if you cast to a typedef:
f( static_cast
(x) ); The point is, if casting is correct, then the implicit conversion is not. If the implicit conversion is correct, then casting is not. You should write the correct code even if that leads to a warning. And if you must silence the warning, you should do it without changing the behavior of a correct program.
If you are writing generic code and do not know the actual type of x, perhaps. In that case you are either relying on overload resolution to find a compatible or matching type among an unknown-to-you overload set (in which case you should not "defend" against warnings because it is the responsibility of whatever code gave you x to ensure that there is a sufficiently compatible overload available to resolve the warning). Or you are trying to enforce conversion to a specific type to call a specific overload known to you, in which case you do the cast (although I think function-style casts are preferred now over static_cast). Or some hybrid of the two, where you don't know x but you do know the possible overload set, in which case you should probably be constraining x to be one of those exact types and then let the implicit or explicit cast happen outside of your code. But for non-generic code where you do know the actual type of x and the possible overloads, then you should already know which one it will call and it's your responsibility to make sure that the right overload exists or to perform the cast to avoid a warning. Either one is equivalent.