简体   繁体   中英

optional constructor with 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); 

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM