gpt4 book ai didi

c++ - 为什么 vector 接受带有整数元素的 initializer_list?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:51:02 25 4
gpt4 key购买 nike

#include <iostream>
#include <vector>

int main()
{
// case I: uniform initialization
//
int ii = 100;
// Error: cannot be narrowed from type 'int' to 'double'
// in initializer list
//
double dd{ ii };

// case II: initializer_list
//
std::vector<double> vecDouble{ 1, 2.2 }; // fine!

// case III: initializer_list
//
std::vector<int> vi = { 1, 2.3 }; // error: double to int narrowing

// case IV: intializer_list
// cannot be narrowed from type 'int' to 'double'
//
std::vector<double> vecD2{ ii, 2.2 }; // Error
}

为什么这里不一致,caseI 不接受 int 到 double 的转换,但 caseII 允许转换。

最佳答案

长话短说,这是有效的,因为从常量表达式转换intdouble 不是缩小转换。换句话说,这与以下代码起作用的原因相同:

double x { 1 };

编译器需要构造std::initializer_list<E>用于花括号初始化。它知道 E 的类型成为double ,因为您正在初始化 std::vector<double> .这在 C++11 标准的第 8.5.4 节中有详细描述。

这是第 8.5.4.3 节中的示例:

struct S {
S(std::initializer_list<double>); // #1
S(const std::string&); // #2
// ...
};
const S& r1 = { 1, 2, 3.0 }; // OK: invoke #1

同一节定义收缩转换如下:

A narrowing conversion is an implicit conversion

  • from a floating-point type to an integer type, or
  • from long double to double or float, or from double to float, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented(even if it cannot be represented exactly), or
  • 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
  • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.

ii 的两个例子属于第三类,即从 int 转换而来至 double当源不是常量表达式时。

关于c++ - 为什么 vector<double> 接受带有整数元素的 initializer_list?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42171550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com