Skip to content

std::optional, std::variant & std::expected

Use C++17/23 sum types to represent nullable values, type-safe unions, and value-or-error returns — eliminating entire classes of bugs at compile time.

Sum Types: Making Invalid States Unrepresentable

A sum type can hold one of several types at any time, and the compiler ensures you handle all possibilities. C++17 introduced std::optional and std::variant; C++23 added std::expected. Together, they replace error-prone patterns:

- std::optional replaces "return T or sentinel value / null pointer"
- std::variant replaces "union + tag enum" (type-safe, no UB)
- std::expected replaces "return T or set error code"

These types move error checking from runtime discipline (hoping the programmer remembers to check) to compile-time enforcement (the type system forces correct handling).

std::optional — Nullable Values Without Pointers

std::optional holds either a T value or nothing (std::nullopt). It replaces the antipattern of using special sentinel values (-1, "", nullptr) to mean "no value".

optional_demo.cpp
#include <optional>
#include <string>
#include <map>
#include <iostream>

class UserDatabase {
public:
    void add(int id, const std::string& name) {
        users_[id] = name;
    }

    // Returns the user name, or std::nullopt if not found
    std::optional<std::string> find_user(int id) const {
        auto it = users_.find(id);
        if (it == users_.end()) {
            return std::nullopt;  // explicit "no value"
        }
        return it->second;  // implicit conversion to optional
    }

private:
    std::map<int, std::string> users_;
};

int main() {
    UserDatabase db;
    db.add(1, "Alice");
    db.add(2, "Bob");

    // Method 1: Check with has_value()
    auto result = db.find_user(3);
    if (result.has_value()) {
        std::cout << "Found: " << result.value() << '\n';
    } else {
        std::cout << "User not found\n";
    }

    // Method 2: value_or() with a default
    std::cout << db.find_user(1).value_or("<unknown>") << '\n';

    // Method 3: Boolean conversion (idiomatic)
    if (auto user = db.find_user(2)) {
        std::cout << "Found: " << *user << '\n';  // dereference like a pointer
    }
}

Monadic Operations on std::optional (C++23)

C++23 adds and_then, transform, and or_else to std::optional, enabling functional-style chaining without nested if statements.

monadic_optional.cpp
#include <optional>
#include <string>
#include <charconv>
#include <iostream>

// C++23 monadic operations on std::optional

std::optional<std::string> get_env(const std::string& name) {
    const char* val = std::getenv(name.c_str());
    if (!val) return std::nullopt;
    return std::string(val);
}

std::optional<int> parse_int(const std::string& s) {
    int value{};
    auto [ptr, ec] = std::from_chars(
        s.data(), s.data() + s.size(), value);
    if (ec != std::errc{}) return std::nullopt;
    return value;
}

std::optional<int> validated_port(int port) {
    if (port > 0 && port < 65536) return port;
    return std::nullopt;
}

int main() {
    // Without monadic ops: nested ifs
    // With monadic ops (C++23): clean pipeline
    int port = get_env("PORT")
        .and_then(parse_int)        // std::optional<int>
        .and_then(validated_port)   // std::optional<int>
        .or_else([]() -> std::optional<int> {
            std::cerr << "Using default port\n";
            return 8080;
        })
        .value();

    std::cout << "Port: " << port << '\n';
}

std::variant — Type-Safe Unions

std::variant holds exactly one of its template types at any time. Unlike C unions, it tracks which type is active and prevents accessing the wrong one. Use std::visit with a visitor to handle all alternatives.

variant_json.cpp
#include <variant>
#include <string>
#include <vector>
#include <iostream>
#include <cmath>

// A JSON-like value type using variant
struct JsonNull {};

using JsonValue = std::variant<
    JsonNull,                           // null
    bool,                               // true/false
    double,                             // number
    std::string,                        // string
    std::vector<struct JsonNode>        // array
>;

struct JsonNode {
    JsonValue value;
};

// Overloaded visitor pattern (C++17 trick)
template<class... Ts>
struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;

std::string to_string(const JsonValue& val) {
    return std::visit(overloaded{
        [](JsonNull) -> std::string { return "null"; },
        [](bool b)   -> std::string { return b ? "true" : "false"; },
        [](double d) -> std::string { return std::to_string(d); },
        [](const std::string& s) -> std::string {
            return "\"" + s + "\"";
        },
        [](const std::vector<JsonNode>& arr) -> std::string {
            std::string result = "[";
            for (std::size_t i = 0; i < arr.size(); ++i) {
                if (i > 0) result += ", ";
                result += to_string(arr[i].value);
            }
            return result + "]";
        }
    }, val);
}

int main() {
    JsonValue v1 = 3.14;
    JsonValue v2 = std::string("hello");
    JsonValue v3 = JsonNull{};

    std::cout << to_string(v1) << '\n';  // 3.140000
    std::cout << to_string(v2) << '\n';  // "hello"
    std::cout << to_string(v3) << '\n';  // null

    // std::holds_alternative and std::get
    if (std::holds_alternative<double>(v1)) {
        std::cout << "v1 is double: " << std::get<double>(v1) << '\n';
    }

    // std::get throws std::bad_variant_access if wrong type
    // std::get_if returns nullptr instead — safer
    if (auto* ptr = std::get_if<std::string>(&v2)) {
        std::cout << "v2 is string: " << *ptr << '\n';
    }
}

std::expected — Value or Error (C++23)

std::expected holds either a value of type T or an error of type E. It is C++'s answer to Rust's Result. Unlike exceptions, the caller must handle the error explicitly. Unlike error codes, the error can carry rich information.

expected_demo.cpp
#include <expected>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <system_error>

enum class ParseError {
    FileNotFound,
    InvalidFormat,
    ValueOutOfRange
};

std::string to_string(ParseError e) {
    switch (e) {
        case ParseError::FileNotFound:   return "file not found";
        case ParseError::InvalidFormat:  return "invalid format";
        case ParseError::ValueOutOfRange: return "value out of range";
    }
    return "unknown";
}

std::expected<std::string, ParseError> read_file(const std::string& path) {
    std::ifstream file(path);
    if (!file.is_open()) {
        return std::unexpected(ParseError::FileNotFound);
    }
    std::ostringstream ss;
    ss << file.rdbuf();
    return ss.str();  // implicitly wraps in expected
}

std::expected<int, ParseError> parse_port(const std::string& content) {
    try {
        int port = std::stoi(content);
        if (port < 1 || port > 65535) {
            return std::unexpected(ParseError::ValueOutOfRange);
        }
        return port;
    } catch (...) {
        return std::unexpected(ParseError::InvalidFormat);
    }
}

int main() {
    // Monadic chaining (C++23)
    auto result = read_file("port.conf")
        .and_then(parse_port)
        .or_else([](ParseError e) -> std::expected<int, ParseError> {
            std::cerr << "Error: " << to_string(e)
                      << ", using default\n";
            return 8080;  // fallback
        });

    std::cout << "Port: " << result.value() << '\n';
}
Pitfall

These types are powerful but have sharp edges if misused.

  • Calling .value() on an empty std::optional throws std::bad_optional_access — always check first or use value_or()
  • std::get(variant) on the wrong type throws std::bad_variant_access — prefer std::visit or std::get_if
  • std::variant with duplicate types (e.g., variant) is valid but confusing — use index-based access only
  • Ignoring the error in std::expected by always calling .value() defeats the purpose — check .has_value() or use monadic operations
  • std::optional does not exist in the standard (yet) — use std::optional> as a workaround
Best Practice

Choose the right sum type for each situation.

  • std::optional: A value that might not exist — lookups, optional parameters, lazy initialization
  • std::variant: A value that could be one of several types — AST nodes, JSON values, message types
  • std::expected: A computation that might fail — file I/O, parsing, validation, anything that returns T or an error
Key Takeaways
  • std::optional replaces sentinel values and null pointers with a type-safe "value or nothing"
  • std::variant replaces C unions with a type-safe tagged union — use std::visit for exhaustive handling
  • std::expected (C++23) is C++'s Result — value or error with monadic chaining
  • C++23 monadic operations (and_then, transform, or_else) enable clean pipelines without nested if blocks
  • Sum types move error checking from runtime discipline to compile-time enforcement

Quiz — Test Your Knowledge

(20 XP)

1. What does `std::optional::value_or(default)` do?

2. What is the advantage of `std::visit` over `std::get<T>` when working with `std::variant`?

3. How does `std::expected<T, E>` differ from simply throwing an exception?