c++returnc++17option-typereturn-type-deduction

If-then-else vs ternary operator when returning full or empty std::optional


(I've not found much by searching for return statement, return deduce, and similar, with tags .)

Why does this work

#include <optional>

auto const f = [](bool b) {
    return b ? std::optional<int>(3) : std::nullopt;
};

while this doesn't?

#include <optional>

auto const f = [](bool b) {
    if (b) {
        return std::optional<int>(3);
    } else {
        return std::nullopt;
    }
};

Why can't the compiler deduce the type from the first return and see it's compatiple with the second return?


Solution

  • Lambda return type deduction require the type of all return expressions match basically exactly.

    ? does a relatively complex system to find a common type of the two cases. There is only one return statement, so so long as ? can figure it out, lambda return type deduction doesn't care.

    Just different rules.

    auto const f = [](bool b)->std::optional<int> {
      if (b) {
        return 3;
      } else {
        return std::nullopt;
      }
    };
    

    this is probably the cleanest.