Yes I know you shouldn't use C style casts in C++, but in some cases I really think it's a lot more readable if you do, compare these two for example:
d = ((double)i * 23.54) / (d + (double)j);
d = (static_cast<double>(i) * 23.54) / (d + static_cast<double>(j));
Which one is more readable?
Now on to my main question. Obviously I prefer the upper one, but there is one way to make it even more readable in my opinion:
d = (double(i) * 23.54) / (d + double(j));
My question here is, will this be less efficient? Will the compiler create more doubles in this case than if they were casted with the other开发者_如何学JAVA methods, or is it clever enough not to? Is this more or less bad than typical C-style casts?
They're all unreadable. You should write:
d = (i * 23.54) / (d + j);
The compiler will "create" exactly the same number of doubles. There is no practical difference between casting to and constructing primitive numeric types.
I have already commented on R's answer about letting the compiler pick out the cast, in this particular case.
There are however cases in which you DO want an explicit conversion:
- you want to prevent overflow or increase precision
- you want to check the validity of the conversion
The Boost Numeric Conversion provides a highly suitable cast here, much better than static_cast
: boost::numeric_cast
- no overhead when no check is required (ie casting from a small to a large integer)
- runtime check of the value when required (ie casting from large to small or signed to unsigned)
It's more readable than static_cast
, since the very nature of the numbers is highlighted, and much safer since it prevents undefined behavior (and portability issues) to kick in.
The reason why cast functions in C++ are long an unwieldy is by design 1) in order to show the user that he's probably doing something wrong 2) in cases when they are necessary, attract attention to that piece of code, that it might be doing something dangerous or unconventional.
IMHO, the static_cast one is more readable, because it provides to the reader information about the nature of the cast.
精彩评论