Skip to content

std::optional

std::optional<int> optVal;                // value not set
std::optional<int> optVal {std::nullopt}; // value not set

// set value
optVal = 42;

// check/get value
if (optVal)
{
    int val = *optVal; // "*" has undefined behaviour if val is not set!
}

if (optVal.has_value())
{
    int val = optVal.value(); // throws exception if val is not set!
}

int val = optVal.value_or(4711); // uses given default if val is not set

Initialize with object and multiple arguments:

std::optional optComplex1 {std::complex{1.0, 2.0}};

// 2 Alternatives avoiding creation of temporary object:
auto optComplex2 = std::make_optional(std::complex{1.0, 2.0});
std::optional<std::complex<double>> optComplex2 {std::in_place, 1.0, 2.0};