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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With