返回完整或空时的 If-then-else 与三元运算符 std::optional

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

(我通过搜索 return statementreturn deduce 和类似,带有标签 .)

为什么这样做

#include <optional>

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

而这不是?

#include <optional>

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

为什么编译器不能从第一个 return 推导出类型并查看它是否与第二个 return 兼容?

Lambda return类型推导要求所有return表达式的类型基本完全匹配。

?做了一个比较复杂的系统,找到两种情况的共同类型。只有一条return语句,只要?能搞定,lambdareturn类型推导无所谓。

只是规则不同。

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

这可能是最干净的。