使用带有一个元素的初始化列表构造std :: vector [英] Construct std::vector using initializer list with one element

查看:76
本文介绍了使用带有一个元素的初始化列表构造std :: vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下程序,定义一个包含值13的std :: vector:

Consider the following program, defining a std::vector containing the value 13:

std::vector<int> vec{13};

这也可能被解释为对构造函数的调用,该构造函数将向量初始化为13个零.我的问题是:编译器如何在使用initializer_list构造std :: vector或通过用13个零初始化矢量之间进行选择?

This could also have been interpreted as a call to the constructor that initializes the vector with 13 zeros. My question is: how does the compiler choose between constructing a std::vector with an initializer_list or by initializing the vector with 13 zeros?

推荐答案

否则,分两个阶段考虑T的构造函数:

Otherwise, the constructors of T are considered, in two phases:

  • 所有将std :: initializer_list用作唯一参数的构造函数,或者将其余参数作为第一个参数的构造函数检查默认值,并通过过载分辨率进行匹配针对类型为std :: initializer_list

  • All constructors that take std::initializer_list as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of type std::initializer_list

如果上一阶段未产生匹配,则T的所有构造函数都将针对以下参数集参与重载解析:由braced-init-list的元素组成,但有限制仅允许非缩小转换.如果这个阶段产生一个显式构造函数,作为与之的最佳匹配复制列表初始化,编译失败(请注意,简单复制初始化,根本不考虑显式构造函数.

If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed. If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all).

这篇关于使用带有一个元素的初始化列表构造std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆