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 ?
You could use the de-reference operator: SomeClass sc = *val; Alternatively, you can use the get() method: SomeClass sc = val.
Boost C++ Libraries Class template optional is a wrapper for representing 'optional' (or 'nullable') objects who may not (yet) contain a valid value. Optional objects offer full value semantics; they are good for passing by value and usage inside STL containers. This is a header-only library.
boost::optional appears to work like a pointer. However, you should not think of boost::optional as a pointer because, for example, values in boost::optional are copied by the copy constructor while a pointer does not copy the value it points to.
A default-constructed boost::optional is empty - it does not contain a value, so you can't call get() on it. You have to initialise it with a valid value: As a side note, you can use -> in place of get() , like this: value->setInt(10);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With