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

Enr*_*lis 4 c++ return optional return-type-deduction c++17

(通过搜索return statementreturn deduce和类似的标签,我没有找到太多的。)

为什么这样做

#include <optional>

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

而这没有?

#include <optional>

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

为什么编译器不能从第一个推断类型return并看到它与第二个兼容return

Yak*_*ont 6

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

?做了一个比较复杂的系统,找到两种情况的共同类型。只有一个 return 语句,只要?能弄明白,lambda 返回类型推导就无所谓了。

只是规则不同。

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

这可能是最干净的。