boost::optional vs boost::make_optional

3.1k Views Asked by At

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!

2

There are 2 best solutions below

0
Woodford On BEST ANSWER

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);
1
Caleth On

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>