问题描述
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
?
推荐答案
因为定义包括b
$ b
Because the definition includes (with my emphasis):
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.
这是实现定义。在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.
这篇关于缩小从无符号到双精度的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!