如何使lambdas与std :: nullopt一起使用

Inc*_*ble 3 c++ lambda return-type-deduction c++17

背景

我有一系列lambda,它们对捕获的变量执行不同的检查,std::nullopt如果检查失败则返回.return 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';
}
Run Code Online (Sandbox Code Playgroud)

Wandbox演示.

思考

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

Rak*_*111 5

而不是使用模板类型推导来推断lambda的返回类型,为什么不明确指定返回类型?

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

    return 2;
};
Run Code Online (Sandbox Code Playgroud)

std::common_type 通常是模板,你没有.

  • @Incomputable我认为委员会故意决定反对.并且有充分的理由IMO; 我们也不允许模板参数推导中的类型不匹配,我们也不应该在这里. (3认同)