gpt4 book ai didi

c++ - 在 vector 构造函数中从 initializer_list 转换为 initializer_list

转载 作者:行者123 更新时间:2023-12-05 01:49:56 32 4
gpt4 key购买 nike

std::vector的初始化列表构造函数具有以下形式

vector( std::initializer_list<T> init, const Allocator& alloc = Allocator() );

是什么使得初始化像std::vector<string> vec{ “foo”, “bar” };可能的?为什么构造函数接受 std::initializer_list<const char*> ,即使 std::vectorsTstd::string ?从哪里以及如何从 std::initializer_list<const char*> 转换至 std::initializer_list<string>发生了什么?

最佳答案

我认为你应该引用 C++ 17 标准(11.6.4 列表初始化)的这一部分

5 An object of type std::initializer_list is constructed from aninitializer list as if the implementation generated and materialized(7.4) a prvalue of type “array of N const E”, where N is the number ofelements in the initializer list. Each element of that array iscopy-initialized with the corresponding element of the initializerlist, and the std::initializer_list object is constructed to referto that array. [ Note: A constructor or conversion function selectedfor the copy shall be accessible (Clause 14) in the context of theinitializer list. — end note ] If a narrowing conversion is requiredto initialize any of the elements, the program is ill-formed. [Example:

struct X {
X(std::initializer_list<double> v);
};
X x{ 1,2,3 };

The initialization will be implemented in a way roughly equivalent tothis:

const double __a[3] = {double{1}, double{2}, double{3}};
X x(std::initializer_list<double>(__a, __a+3));

assuming that the implementation can construct an initializer_listobject with a pair of pointers. — end example ]

注意有std::basic_string类的转换构造函数

basic_string(const charT* s, const Allocator& a = Allocator());

所以在这个声明中

std::vector<string> vec{ “foo”, “bar” };

首先是一个 std::initializer_list<std::string> 类型的对象由初始化列表构造,然后用作 std::vector<std::string> 类型的 vector 的初始化器.

如果相反你会写

std::initializer_list<const char *> lst = { "foo", "bar" };
std::vector<std::string> vec( lst );

然后编译器将发出错误,因为没有从类型 std::initializer_list<const char *> 进行隐式转换到类型std::initializer_list<std::string> .

即编译器决定是否可以构建std::initializer_list从花括号初始化器列表调用初始化器列表构造函数。

关于c++ - 在 vector 构造函数中从 initializer_list<const char*> 转换为 initializer_list<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73614093/

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