缩小从无符号到双精度的转换 [英] narrowing conversion from unsigned to double
问题描述
static_assert(sizeof(unsigned) == 4, ":(");
static_assert(sizeof(double) == 8 ,":(");
unsigned u{42};
double x{u};
g ++ 4.7。 1抱怨这个代码:
g++ 4.7.1 complains about this code:
warning: narrowing conversion of 'u' from 'unsigned int' to 'double' inside { }
为什么这是一个缩小的转换?不是每个无符号
完美表示为 double
?
Why is this a narrowing conversion? Isn't every unsigned
perfectly representable as a double
?
推荐答案
为什么这是缩小的转换?
Why is this a narrowing conversion?
因为定义包括b
$ b
Because the definition includes (with my emphasis):
C ++ 11 8.5.4 / 7 缩小转换次数是隐式转换
[...]从整数类型[...]更改为浮点类型,除非源是常量表达式,转换后的实际值将适合目标类型,
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
不是常量表达式,因此无论源类型的所有可能值是否都可以在目标类型中表示,它是一个缩小的转换。
u
is not a constant expression, so it's a narrowing conversion whether or not all possible values of the source type might be representable in the target type.
不是每个
无符号
完美表示为double
?
这是实现定义。在32位 unsigned
和 double
与52位尾数的通用情况下,情况是这样;但是一些实现具有更大的 unsigned
和/或更小的 double
表示,因此依赖于该假设的代码是不可移植的。
That's implementation defined. In the common case of 32-bit unsigned
and double
with a 52-bit mantissa, that is the case; but some implementations have larger unsigned
and/or smaller double
representations, so code that depends on that assumption is not portable.
这篇关于缩小从无符号到双精度的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!