为什么这段代码中没有窄化转换,导致错误
Why is there no narrowing conversion in this code, resulting in an error?
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]
相关文章:
- C++使用params创建线程函数会导致转换错误
- 为什么g++在未执行的代码处标记强制转换错误
- 为什么C++在将浮点数转换为字符时没有显示缩小转换错误?
- 如何在构建对象堆栈时解决转换错误?
- 执行具有转换错误的过程
- 指向类成员函数的指针中存在类型转换错误
- 为什么我在这里收到C++没有已知的转换错误?
- 增加图形转换错误
- 尝试向 COM 对象添加另一个接口时出现静态强制转换错误 C2440
- 返回带有另一个类的数据成员的构造函数?遇到转换错误?
- 指针和双重转换错误,代码没有
- 自定义函数转换错误?
- 将 C 程序转换为具有大量字符* 和无符号字符转换错误的C++
- 如何在我使用过的Arduino库之一中固定构造函数中的转换错误
- 试图使用strCMP时的char转换错误
- 我在 TSP 的C++解决方案中遇到转换错误
- "double(*)(string, double, double)"尝试传递函数C++时"double"转换错误
- 此语法中的构造函数转换错误
- Opengl 精度转换错误编译错误 E0415
- 无效的转换错误和无效的类型