C++ std::optional
#include <iostream>
#include <optional>
int main() {
std::optional<int> maybeValue;
if (maybeValue.has_value()) {
std::cout << "Value is present: " << maybeValue.value() << std::endl;
} else {
std::cout << "No value present" << std::endl;
}
maybeValue = 42;
if (maybeValue.has_value()) {
std::cout << "Value is present: " << maybeValue.value() << std::endl;
} else {
std::cout << "No value present" << std::endl;
}
return 0;
}
Explanation:
#include <iostream>
and#include <optional>
: Include necessary header files for input/output operations and thestd::optional
class.std::optional<int> maybeValue;
: Declare an optional variable namedmaybeValue
that can hold an integer. It is initially uninitialized.if (maybeValue.has_value()) { ... } else { ... }
: Check if the optional variable has a value using thehas_value()
member function. Print whether a value is present or not.maybeValue = 42;
: Assign a value of 42 to the optional variable.Repeat the check for value presence using
if (maybeValue.has_value()) { ... } else { ... }
after assigning a value, and print the updated status.return 0;
: Indicates successful program execution.