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

How to make lambdas work with std::nullopt

背景

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

问题

return表达式的类型不一致,例如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';
}

Wandbox Demo.

想法

我认为我需要在某处使用 std::common_type<Args...>,但我无法强制使用它或推断 Args,因为它可能需要语言支持。

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

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

    return 2;
};

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

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

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