Skip to content

Optional

Optional

The class template std::optional manages an optional contained value, i.e. a value that may or may not be present.

A common use case for optional is the return value of a function that may fail. As opposed to other approaches, such as std::pair, optional handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly.

Any instance of optional<T> at any given point in time either contains a value or does not contain a value.

1
2
3
4
5
6
7
8
std::optional<int> get_even_random_number() {
    int i = std::rand();
    if (i % 2 == 0) {
        return i;
    } else {
        return std::nullopt;
    }
}

1
2
3
4
std::optional<int> get_even_random_number2() {
    int i = std::rand();
    return std::make_optional(int(i % 2 == 0));
}

1
2
3
4
5
6
std::optional<int> i = get_even_random_number();
if (i) {
    std::cout << std::sqrt(static_cast<float>(*i)) << '\n';
} else {
    std::cout << "No value was returned" << '\n';
}

1
2
3
4
i = get_even_random_number2();
double d = i.value_or(0);
std::cout << std::sqrt(d) << '\n';
std::cout << i.value_or(0) << std::endl;

Share Snippets