Table of Contents

<optional>

<optional> represents a value that may or may not be present, a type-safe alternative to returning a null pointer or sentinel value. Use .has_value() or the conversion operator to check, and .value() or * to access the contained value.

It's useful for functions that may fail to produce a value but don't need to throw or use exceptions.

Example

This example uses optional to return either a found integer or nothing, with type-safe checking and extraction.

// compile: g++ -std=c++17 -o optionalexample optionalexample.cpp
// run: ./optionalexample
// description: optional value handling
 
#include <optional>
#include <iostream>
#include <string>
 
std::optional<int> find_value(const std::string& key) {
    if (key == "answer") {
        return 42;
    }
    return std::nullopt;
}
 
int main() {
    auto result = find_value("answer");
    if (result.has_value()) {
        std::cout << "found: " << result.value() << "\n";
    }
 
    auto missing = find_value("unknown");
    if (!missing) {
        std::cout << "not found\n";
    }
 
    return 0;
}