使用 g++ 和 clang 都可以编译
std::vector<int> xs{1, 2, 3u};
但是编译不行
std::vector<int> xs{1, 2, 3.0};
这个看似奇怪的选择背后的理由是什么?
如果我们同时考虑最后一个值的类型unsigned
,并且double
不能安全地转换为 an int
,并且如果我们同时考虑特定的文字值,3u
并且3.0
可以安全地转换。
那为什么要区分呢?
正式规范说,如果可以表示值,则允许从整数或枚举转换为不同的它,甚至允许从丢失数据的文字进行转换(例如double
转换为float
)。有趣的是,这会导致:
std::vector<float> x{1073741824}; // ok, value can be represented
std::vector<float> y{1073741823}; // not ok, narrowing
std::vector<float> z{1073741823.}; // ok (even if loses precision!)
std::vector<int> w{3.0}; // not ok, just because