Sometimes, we need to explicitly cast one numeric type to another (e.g. to avoid warning when we lose precision or range). For some:
double foo;
we could write:
(float)foo
but most C++ programmers say it's evil 'old-style cast' and you should use the 'new-style cast':
static_cast<float>(foo)
There is an alternative of boost::numeric_cast
which is quite interesting (at least in not-performance-critical code) but this question is about static_cast
.
A similar question was already asked, but the most important arguments used there are not valid for numerical cast (in my opinion, am I wrong?). There are they:
You have to explicitly tell the compiler what you want to do. Is it upcast, or downcast? Maybe reinterpret cast?
No. It is simple numeric cast. There is no ambiguity. If I know how static_cast<float>
works, I know how does it work for 'old-style' cast.
When you write (T)foo
you don't know what T
is!
I'm not writting (T)foo
but (float)foo
. I know what is float
.
Are there any important reasons for using a new, better casts for numeric types?