Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieving an object from boost::optional

Tags:

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 ? 
like image 815
MistyD Avatar asked Jun 05 '13 19:06

MistyD


People also ask

How do I get the value of a boost optional?

You could use the de-reference operator: SomeClass sc = *val; Alternatively, you can use the get() method: SomeClass sc = val.

What is boost :: optional in C++?

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.

How boost optional works?

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.

How do I initialize a boost optional?

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);


1 Answers

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.

like image 163
juanchopanza Avatar answered Sep 21 '22 06:09

juanchopanza