在我目前正在进行的项目中,我发现自己编写了很多如下所示的代码,其中get_optional_foo
返回一个 std::optional :
//...
auto maybe_foo = get_optional_foo(quux, ...)
if (!maybe_foo.has_value())
return {};
auto foo = maybe_foo.value()
//...
// continue on, doing things with foo...
如果我得到一个空选项,我想退出该功能;否则,我想为该值分配一个非可选变量。我已经开始使用使用maybe_
前缀命名可选的约定,但我想知道是否有某种方法可以做到这一点,这样我就不需要为可选的临时使用?此变量仅用于检查空选项并在有值时取消引用。