问题描述
在我目前正在从事的项目中,我发现自己编写了许多类似于以下内容的代码,其中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_
前缀命名可选内容的约定,但是我想知道是否有某种方法可以使我完全不需要为可选内容使用临时名称?此变量仅用于检查null选项并在存在值时取消引用。
解决方法
您不需要中间对象。 std::optional
支持一个指针接口来访问它,因此您可以像这样使用它:
//...
auto foo = get_optional_foo(quux,...)
if (!foo)
return {};
//...
foo->some_member;
(*foo).some_member;
,
我能想到的最短的
auto maybe_foo = get_optional_foo(quux,...)
if (!maybe_foo) return {};
auto &foo = *maybe_foo; // alternatively,use `*maybe_foo` below
如果函数中有多个可选项,并且它们不太可能为空,则可以用try - catch
包装整个内容。
try {
auto &foo = get_optional_foo(quux,...).value();
auto &bar = get_optional_bar(...).value();
...
} catch (std::bad_optional_access &e) {
return {};
}
,
与您要问的内容略有不同,但请考虑:
if (auto foo = get_optional_foo(1)) {
// ...
return foo->x;
} else {
return {};
}
这会将函数的主体放置在if()
块中,该块可能更具可读性。