std::vector
的初始化列表构造函数具有以下形式
vector( std::initializer_list<T> init, const Allocator& alloc = Allocator() );
是什么使得初始化像std::vector<string> vec{ “foo”, “bar” };
可能的?为什么构造函数接受 std::initializer_list<const char*>
,即使 std::vectors
的T
是std::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 an initializer list as if the implementation generated and materialized (7.4) a prvalue of type “array of N const E”, where N is the number of elements in the initializer list. Each element of that array is copy-initialized with the corresponding element of the initializer list, and the std::initializer_list object is constructed to refer to that array. [ Note: A constructor or conversion function selected for the copy shall be accessible (Clause 14) in the context of the initializer list. — end note ] If a narrowing conversion is required to 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 to this:
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_list object 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/