如何声明一个返回std::optionallambda 的函数?例如
<what_do_i_put_here?> foo(bool b) {
if(b) return std::nullopt;
return [](int) { ... };
}
Run Code Online (Sandbox Code Playgroud)
使用三元运算符怎么样?它会自动推导出正确的optional类型
#include <optional>
auto foo(bool b) {
return b ? std::nullopt : std::optional{[](int){}};
}
Run Code Online (Sandbox Code Playgroud)
您可以添加间接级别以通过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)