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 中,不包括您的示例
from an integer type or unscoped enumeration 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, or …
(强调我的)
关于c++ - 为什么这段代码没有收缩转换,导致错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15297191/