int64_t a = 1234;
double d = (double) a;
Is this the recommended way?
You can also use the conversion syntax, which is equivalent to a static_cast:
int64_t a = 1234;
double d = double(a);
This is a useful syntactic construction in that it allows primitive and class types to be treated the same way in template code, either doing a static_cast, for the primitive, or invoking a constructor, for the class type.
use static_cast
as strager answers. I recommend against using the implicit cast (or even a C-style cast in C++ source code) for a few reasons:
static_cast
makes your intent immediately obvious.static_cast
and the other C++-style casts are easy for grep
to handle.You should use static_cast
or rely on the implicit cast instead:
int64_t a = 1234;
double d = static_cast<double>(a);
double f = a;
For POD types both versions do the same thing. Choose the one you prefer and be consistent.
I know many people who prefer the former for typing/readability and I tend to agree with this but I can live with either.
I've heard the "easy to grep for" argument many times but have yet to ever come across a situation where I've needed to grep my codebase for POD casts.