Reputation: 127
I would like to understand better the difference between creating a boost::optional object using the default constructor:
boost::optional<PastaType> pasta = boost::optional<PastaType>(spaghetti)
or using the make_optional version:
boost::optional<PastaType> pasta = boost::make_optional<PastaType>(spaghetti)
Looking around I just understoood that with the make_optional version PastaType cannot be a reference type, but I would like to figure out better when to use one or the other.
Thanks!
Upvotes: 4
Views: 3918
Reputation: 62636
Prior to C++17, you couldn't deduce template arguments for a class from it's initialisation, like you could with a function template call.
As a workaround, functions named in the form make_thing
that constructed a thing
allowed deduction.
auto pasta = boost::make_optional(spaghetti); // pasta is boost::optional<PastaType>
auto pasta = boost::optional(spaghetti); // compile error before C++17, afterward pasta is boost::optional<PastaType>
Upvotes: 4
Reputation: 4449
make_optional
is a convenience or helper function that can reduce the amount of code you have to write by inferring the template parameter of optional
. Functionally the two methods are equivalent.
auto pasta = boost::make_optional(spaghetti);
Upvotes: 4