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 ?
3 个解决方案
#1
21
You could use the de-reference operator:
您可以使用de-reference运算符:
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对象的左值引用。
#2
9
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*/)
#3
4
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.
另一种方法是函数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可用于指定在未设置值的情况下返回的默认值。
#1
21
You could use the de-reference operator:
您可以使用de-reference运算符:
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对象的左值引用。
#2
9
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*/)
#3
4
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.
另一种方法是函数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可用于指定在未设置值的情况下返回的默认值。