std::optional Creation
Explore multiple ways to create std optional in C++17, including initializing as empty, directly with a value, using deduction guides, make optional, and in_place. Understand how these methods simplify handling nullable and complex types effectively.
We'll cover the following...
We'll cover the following...
There are several ways to create std::optional:
- Initialise as empty
- Directly with a value
- With a value using deduction guides
- By using
make_optional - With
std::in_place - From other
optional
See code below:
As you can see in the above code sample, you have a lot of flexibility with the creation of optional. It’s straightforward for primitive types, and this simplicity is extended even to complex types.
And, if you want the full control over the creation and efficiency, it’s also good to know in_place
helper types. We’ll tackle that next.