如何返回 std::可选 lambda?

Bar*_*uch 2 c++ lambda c++17

如何声明一个返回std::optionallambda 的函数?例如

<what_do_i_put_here?> foo(bool b) {
    if(b) return std::nullopt;
    return [](int) { ... };
}
Run Code Online (Sandbox Code Playgroud)

康桓瑋*_*康桓瑋 7

使用三元运算符怎么样?它会自动推导出正确的optional类型

#include <optional>
auto foo(bool b) {
  return b ? std::nullopt : std::optional{[](int){}};
}
Run Code Online (Sandbox Code Playgroud)


for*_*818 5

您可以添加间接级别以通过auto和推断类型decltype

#include <optional>

auto foo_impl(){
    return [](int){};
}

std::optional<decltype(foo_impl())> foo(bool b) {
    if(b) return std::nullopt;
    return foo_impl();
}
Run Code Online (Sandbox Code Playgroud)