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

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

为什么这样做

#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 语句,只要?能弄明白,lambda 返回类型推导就无所谓了。

只是规则不同。

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

这可能是最干净的。


以上是返回完整或空std::optional时的If-then-else与三元运算符的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>