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:

  1. #include <iostream> and #include <optional>: Include necessary header files for input/output operations and the std::optional class.

  2. std::optional<int> maybeValue;: Declare an optional variable named maybeValue that can hold an integer. It is initially uninitialized.

  3. if (maybeValue.has_value()) { ... } else { ... }: Check if the optional variable has a value using the has_value() member function. Print whether a value is present or not.

  4. maybeValue = 42;: Assign a value of 42 to the optional variable.

  5. Repeat the check for value presence using if (maybeValue.has_value()) { ... } else { ... } after assigning a value, and print the updated status.

  6. return 0;: Indicates successful program execution.