C++ 从 boost::optional 检索对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16948715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
retrieving an object from boost::optional
提问by MistyD
Suppose a method returns something like this
假设一个方法返回这样的东西
boost::optional<SomeClass> SomeMethod()
{...}
Now suppose I have something like this
现在假设我有这样的事情
boost::optional<SomeClass> val = SomeMethod();
Now my question is how can I extract SomeClass out of val ?
现在我的问题是如何从 val 中提取 SomeClass ?
So that I could do something like this:
这样我就可以做这样的事情:
SomeClass sc = val ?
回答by juanchopanza
You could use the de-reference operator:
您可以使用取消引用运算符:
SomeClass sc = *val;
Alternatively, you can use the get()
method:
或者,您可以使用以下get()
方法:
SomeClass sc = val.get();
Both of these return an lvalue reference to the underlying SomeClass
object.
这两个都返回对底层SomeClass
对象的左值引用。
回答by Timothy Shields
To check if the optional contains a value, and the optionally retrieve it:
要检查可选项是否包含一个值,并可选地检索它:
boost::optional<SomeClass> x = SomeMethod();
if (x)
x.get();
To get the optional value, or a default value if it does not exist:
要获取可选值或默认值(如果不存在):
SomeMethod().get_value_or(/*default value*/)
回答by SebastianK
As mentioned in the previous answers, the de-reference operator and the function get()
have the same functionality. Both require the optional to contain valid data.
正如前面的答案中提到的,取消引用运算符和函数get()
具有相同的功能。两者都需要可选以包含有效数据。
if (val)
{
// the optional must be valid before it can be accessed
SomeClass sc1 = *val;
SomeClass sc2 = val.get();
}
An alternative is the function value()
, that throws an exception if the optional does not carry a value.
另一种方法是 function value()
,如果可选项不携带值,则抛出异常。
// throws if val is invalid
SomeClass sc3 = val.value();
Alternatively, the functions value_or
and value_or_eval
can be used to specify defaults that are returned in case the value is not set.
或者,函数value_or
和value_or_eval
可用于指定在未设置值的情况下返回的默认值。