c++ - 缩小从无符号到 double 的转换

标签 c++ c++11 warnings double type-conversion

static_assert(sizeof(unsigned) == 4, ":(");
static_assert(sizeof(double) == 8 ,":(");
unsigned u{42};
double x{u};

g++ 4.7.1 提示此代码:

warning: narrowing conversion of 'u' from 'unsigned int' to 'double' inside { }

为什么这是一个缩小转换?不是每个 unsigned 都可以完美地表示为 double 吗?

最佳答案

Why is this a narrowing conversion?

因为定义包括(我强调):

C++11 8.5.4/7 A narrowing conversion is an implicit conversion [...] from an integer type [...] to a floating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type.

u 不是常量表达式,因此无论源类型的所有可能值是否都可以在目标类型中表示,它都是一种缩小转换。

Isn't every unsigned perfectly representable as a double?

这是定义的实现。在常见的32位unsigneddouble带52位尾数的情况下,就是这样;但有些实现有较大的 unsigned 和/或较小的 double 表示,因此依赖于该假设的代码是不可移植的。

关于c++ - 缩小从无符号到 double 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11521016/

相关文章:

javascript - 添加附加功能以退出页面弹出消息

c++ - 我们能否将规范性引用中未明确引用的内容应用于 C++ 标准?

java - Eclipse - 如何仅对特定文件夹而不是整个项目设置 javadoc 警告

c++ - (OpenCV/DNN) 面部识别不起作用 - 欧氏距离始终为 0

java - corrupted double-linked list error 第一次运行程序时,后续运行正常

c++ - 从模板方法返回在模板类内部声明的结构

c++11 - 将枚举类作为构造函数的参数传递

ios - 警告 : Attempting to create USE_BLOCK_IN_FRAME

c++ - VC++ 实验模块不起作用

c++ - 如何显式提及 std::vector 的构造函数?