C++ 将 int64_t 转换为双精度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/691935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:47:17  来源:igfitidea点击:

Convert int64_t to double

c++type-conversion

提问by kal

  int64_t a = 1234;

  double d = (double) a;

Is this the recommended way?

这是推荐的方式吗?

回答by Tom

use static_castas strager answers. I recommend againstusing the implicit cast (or even a C-style cast in C++ source code) for a few reasons:

使用static_cast作为strager答案。我建议不要使用隐式转换(甚至 C++ 源代码中的 C 样式转换),原因如下:

  • 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_castmakes your intentimmediately obvious.
  • static_castand the other C++-style casts are easy for grepto handle.
  • 隐式强制转换是编译器警告的常见来源,这意味着您可能会在构建中添加噪音(现在或稍后添加更好的警告标志时)。
  • 您身后的下一个维护程序员将看到一个隐式转换,并且需要知道这是故意行为还是错误/错误。有了这个static_cast,你的意图就很明显了。
  • static_cast其他 C++ 风格的类型转换很容易grep处理。

回答by strager

You should use static_castor rely on the implicit cast instead:

您应该使用static_cast或依赖隐式转换:

int64_t a = 1234;
double d = static_cast<double>(a);
double f = a;

回答by Andrew Grant

For POD types both versions do the same thing. Choose the one you prefer and be consistent.

对于 POD 类型,两个版本都做同样的事情。选择您喜欢的一种并保持一致。

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.

我已经多次听到“易于 grep for”的论点,但还没有遇到过需要为 POD 强制转换我的代码库的情况。

回答by dcw

You can also use the conversion syntax, which is equivalent to a static_cast:

您还可以使用转换语法,它等效于 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.

这是一个有用的语法构造,因为它允许在模板代码中以相同的方式处理原始类型和类类型,或者为原始类型执行 static_cast,或者为类类型调用构造函数。