retrieving an object from boost::optional

MistyD picture MistyD · Jun 5, 2013 · Viewed 24.9k times · Source

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 ?

Answer

juanchopanza picture juanchopanza · Jun 5, 2013

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.