如何使lambda与std::nullopt一起工作

How to make lambdas work with std::nullopt

本文关键字:nullopt 工作 一起 std 何使 lambda      更新时间:2023-10-16

Background

我有一系列 lambda 对捕获的变量执行不同的检查,如果检查失败,则返回std::nulloptreturn std::nullopt是第一个返回语句。然后,如果检查成功,他们继续计算值。

问题

返回表达式的类型不一致,例如std::nullopt_t不能转换为std::optional<T>,即使反过来有效。特别是,我希望编译和运行以下代码,打印 2:

#include <functional>
#include <utility>
#include <optional>
int x = 3;
auto lambda = [](){
if (x == 2)
return std::nullopt;
return std::optional(2);
};
#include <iostream>
int main () {
using return_type = std::invoke_result_t<decltype(lambda)>;
static_assert(std::is_same<return_type, std::optional<int>>{}, 
"return type is still std::nullopt_t");
std::cout << lambda().value() << 'n';
}

魔杖盒演示。

思潮

我相信我需要在某处使用std::common_type<Args...>,但我既不能强制存在它,也不能推断Args,因为它可能需要语言支持。

与其使用模板类型推导来推断 lambda 的返回类型,为什么不显式指定该返回类型?

auto lambda = []() -> std::optional<int> {
if (x == 2)
return std::nullopt;
return 2;
};

std::common_type通常使用模板,而您没有模板。

我建议坚持使用单个返回语句和显式指定的结果类型,而无需使用 nullopt。当函数返回整数或 nullopt 时,它看起来有些误导。特别是如果功能更长。此外,如果值类型是具有显式构造函数的东西,则使用emplace可以避免再次键入值类型名称。

auto lambda = []()
{
std::optional<int> result{};
if(2 != x)
{
result.emplace(2);
}
return result;
};