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 adouble
?
这是实现定义的。在 32 位 unsigned
和带有 52 位尾数的 double
的常见情况下,就是这种情况;但是一些实现具有更大的 unsigned
和/或更小的 double
表示,因此依赖于该假设的代码不可移植。
关于c++ - 缩小从 unsigned 到 double 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38228357/