为什么这段代码中没有窄化转换,导致错误

Why is there no narrowing conversion in this code, resulting in an error?

本文关键字:转换 错误 段代码 代码 为什么      更新时间:2023-10-16

g++-std=c++11似乎接受了:

#include <vector>
#include <initializer_list>
std::vector<float> vf={1,2,3}; // Isn't this narrowing (i.e., an error)?
int main() {}

看起来有注释的那一行应该出错,但它没有。

感谢Jesse指出了标准(8.5.4 p7),该标准定义了为什么这样做是可以的。下面是一些示例代码,它们有助于澄清标准定义的行为:

const int v5=5;
int v6=6;
vector<double> vd1={1,2,3,4};       // OK
vector<double> vd2={1,2,3,4,v5};    // Still OK, v5 is const
vector<double> vd3={1,2,3,4,v5,v6}; // Error, narrowing conversion, because v6 
                                    // is non-const
vector<double> vd4={1,2,3,4,v5,static_cast<const int>(v6)}; // Also errors on 
                                    // gcc 4.7.2, not sure why.

我希望我刚才给出的例子能帮助其他人在使用初始化器列表时克服一些狭窄的问题。

如果有人知道为什么最后一个例子违反了标准定义,请发表评论。

规则在8.5.4 p7中,不包括你的例子

从整数类型或无作用域枚举类型转换为浮点数输入,除非源是常量表达式和实际的转换后的值将适合目标类型并产生转换回原始类型或& help;

时的原始值

<一口>(强调我的)

既然这三个整数都可以精确地表示为float,我不明白为什么会出错。

也就是说,如果我包含一个不适合float的常量,我可以让g++给我一个警告:

warning: narrowing conversion of '2112112112' from 'int' to 'float' inside { } [-Wnarrowing]