gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:05:15 26 4
gpt4 key购买 nike

(通过搜索带有标签 的 return 语句、return 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 语句,只要 ?可以弄清楚,lambda 返回类型推导无关紧要。
只是规则不同。

auto const f = [](bool b)->std::optional<int> {
if (b) {
return 3;
} else {
return std::nullopt;
}
};
这可能是最干净的。

关于c++ - 返回完整或空 std::optional 时的 If-then-else 与三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67561571/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com