mercredi 7 avril 2021

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;

Aucun commentaire:

Enregistrer un commentaire