27

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 ?
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
MistyD
  • 16,373
  • 40
  • 138
  • 240

3 Answers3

31

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.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
11

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*/)
Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
8

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.

SebastianK
  • 3,582
  • 3
  • 30
  • 48