Search code examples
c++boostboost-optional

retrieving an object from boost::optional


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 ?

Solution

  • 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.