optional constructor with initializer_list

假如想象 提交于 2019-11-28 12:00:40

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);

you wouldn't be able to construct an optional as

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

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);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!