26
votes

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 ?

So that I could do something like this:

SomeClass sc = val ?
3

3 Answers

30
votes

You could use the de-reference operator:

SomeClass sc = *val;

Alternatively, you can use the get() method:

SomeClass sc = val.get();

Both of these return an lvalue reference to the underlying SomeClass object.

11
votes

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*/)
7
votes

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.

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(), which throws an exception if the optional does not carry a 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.