Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 299
balki Avatar asked Dec 03 '14 03:12

balki


1 Answers

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.

like image 167
Praetorian Avatar answered Oct 26 '22 15:10

Praetorian