Convert int64_t to double

前端 未结 4 1724
野趣味
野趣味 2021-02-07 05:31
  int64_t a = 1234;

  double d = (double) a;

Is this the recommended way?

相关标签:
4条回答
  • 2021-02-07 05:50

    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.

    0 讨论(0)
  • 2021-02-07 05:54

    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:

    • Implicit casts are a common source of compiler warnings, meaning you may be adding noise to the build (either now, or later when better warning flags are added).
    • The next maintenance programmer behind you will see an implicit cast, and needs to know if it was intentional behavior or a mistake/bug. Having that static_cast makes your intent immediately obvious.
    • static_cast and the other C++-style casts are easy for grep to handle.
    0 讨论(0)
  • 2021-02-07 05:56

    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;
    
    0 讨论(0)
  • 2021-02-07 06:10

    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.

    0 讨论(0)
提交回复
热议问题