c++ - 为什么这段代码没有收缩转换,导致错误?

标签 c++ c++11

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/

相关文章:

c++ - 根据它们在 C++ 中作为矩阵的位置从文件中读取数字

c++ - 如何随机洗牌 map 中的值?

c++ - 关闭应用程序是否释放在 C++ 中使用 new 分配的空间?

C++11 lambda : mixed capture list

c++ - 复杂范围的多个迭代器

c++ - 简单程序省略的第一个字符

c++ - 在可变参数模板中使用垫片的更简洁的方法?

c++ - 如何在 std::function 中存储 std::sqrt

c++ - 快速将 '0 1 1 0 1'格式的字符串转成bitset

c++ - 在 x 时间后结束循环的最低性能密集方式