构造具有初始化器迭代器列表的容器 [英] Construct container with initializer list of iterators

查看:141
本文介绍了构造具有初始化器迭代器列表的容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用迭代器范围构造向量,如下所示:

It's possible to construct a vector with an iterator range, like this:

std::vector<std::string> vec(std::istream_iterator<std::string>{std::cin},
                             std::istream_iterator<std::string>{});



< ,如下所示:

But I can also compile and run code using C++11 uniform initialization syntax (note the bracers), like this:

std::vector<std::string> vec{std::istream_iterator<std::string>{std::cin},
                             std::istream_iterator<std::string>{}};

这里真正发生了什么?

我知道一个构造函数取初始化列表优先于其他形式的构造。不应该编译器解析到构造函数,接受包含 std :: istream_iterator 的2个元素的初始化器列表?这应该是一个错误,因为 std :: istream_iterator 不能转换为向量值类型 std :: string ,<?p>

I know that a constructor taking an initializer list gets priority over other forms of construction. Shouldn't the compiler resolve to the constructor taking an initializer list containing 2 elements of std::istream_iterator? This should be an error as a std::istream_iterator can't be converted to the vectors value type std::string, right?

推荐答案

从§13.3.2/ 1([over.match.list])

From §13.3.2/1 ([over.match.list])


当非聚合类类型 T 的对象被列表初始化时
4),重载解析在两个阶段中选择构造函数:

When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases:

- 最初,候选函数是初始化列表
构造函数类 T ,参数列表由
初始化列表组成一个参数。

— Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of the initializer list as a single argument.

- 如果没有可行的
初始化列表构造函数,重载解析是
再次执行,其中候选函数都是$ b $ T 的b个构造函数,参数列表由初始化器列表的
个元素组成。

— If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.

在你的情况下,初始化列表构造函数被认为是不可行的(因为 std :: istream_iterator< std :: string> std :: string ),第二个条件适用。这将导致构造函数选择2个迭代器。

In your case the initializer list constructor is deemed non-viable (because std::istream_iterator<std::string> is not convertible to std::string), and the second condition applies. This results in the constructor taking 2 iterators to be selected.

这篇关于构造具有初始化器迭代器列表的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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