Search code examples
c++c++11boostoption-type

Initialize boost::optional with ternary operator


Is the a way to initialize optional like:

bool conditional = true;
boost::optional<int> opt = conditional ? 5 : boost::none;

Why does the error occur?:

main.cpp:31:31: error: operands to ?: have different types ‘int’ and ‘const boost::none_t’
boost::make_optional(cond ? 5 : boost::none);
      |                          ~~~~~^~~~~~~~~~~~~~~~~

With simple if else I can do this:

boost::optional<int> opt;
if (cond)
    opt = 5;
else
    opt = boost::none;

Solution

  • The ternary operator requires the left & right to be the same (or convertible) types. none_t and int aren't the same type. You can probably do cond ? boost::optional<int>(5) : boost:none

    I don't use boost, so just guessing on syntax based on std::optional, but the following does work:

    std::optional<int> opt = cond ? std::optional<int>(5) : std::nullopt;