带有initializer_list的可选构造函数 [英] optional constructor with initializer_list

查看:129
本文介绍了带有initializer_list的可选构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个特殊的构造函数使用初始化列表的目的是什么.有人可以举个例子说明什么时候会有用吗?

What is the purpose of this special constructor taking initializer list. Can someone give an example of when this will be useful?

template <class U, class... Args>
constexpr explicit optional(in_place_t, initializer_list<U> il, Args&&... args);

以上内容与此有何不同?

How is the above different from this?

template <class... Args> 
constexpr explicit optional(in_place_t, Args&&... args); 

参考: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3793.html#optional.object.ctor

P.S.不确定使用c ++ 14还是c ++ 1z标签.我认为应该有c ++技术规范的标签

P.S. Not sure whether to use c++14 or c++1z tag. I think there should be tag for c++ techinical specification

推荐答案

使用两个单独的构造函数的原因是允许构造以initializer_list作为其构造函数参数的对象(可以选择在其后跟随任意参数列表) .假设您有一个类型如下的foo:

The reason for the two separate constructors is to allow construction of objects that take an initializer_list as their constructor argument (optionally followed by an arbitrary list of arguments). Say you have a type foo that looks like this:

struct foo
{
    foo(std::initializer_list<int>) {}
};

在没有构造函数的情况下

In the absence of the constructor

template <class U, class... Args>
constexpr explicit optional(in_place_t, initializer_list<U> il, Args&&... args);

您将无法将optional构造为

optional<foo> o(in_place, {1, 2, 3});

以上操作失败,因为 braced-init-list 没有类型,因此模板参数推导失败.您将不得不诉诸于此:

The above fails because a braced-init-list has no type, so template argument deduction fails. You'd have to resort to something like this:

auto il = {1, 2, 3};
optional<foo> o(in_place, il);

在构造optional对象时,具有接受initializer_list参数的构造函数可以使语法更加自然.

Having the constructor that accepts the initializer_list argument allows a more natural syntax when constructing the optional object.

这是一个最小示例,它展示了这两个构造函数的效用.

Here's a minimal example demonstrating the utility of the two constructors.

这篇关于带有initializer_list的可选构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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