Skip to main content

Lesson 4 of 7

std::optional, std::variant & structured bindings

`std::optional<T>` (C++17) represents a value that **may or may not exist** - a cleaner alternative to nullable pointers or sentinel values. `std::variant<T, U, V>` is a **type-safe union** - holds exactly one of a set of types at a time, with no undefined behaviour. `std::visit` provides pattern-matching-style dispatch. **Structured bindings** (C++17) unpack `std::tuple`, `std::pair`, `std::array`, or any struct with all-public members.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

optional, variant & Structured Bindings Patterns

optional, variant & Structured Bindings Patterns
#include <iostream>
#include <optional>
#include <variant>
#include <string>
#include <map>
#include <sstream>

// ── std::optional - nullable without raw pointers ───────────
std::optional<int> parse_int(const std::string& s) {
    try {
        size_t idx;
        int val = std::stoi(s, &idx);
        if (idx != s.size()) return std::nullopt;  // trailing garbage
        return val;
    } catch (...) {
        return std::nullopt;
    }
}

std::optional<std::string> read_env(const std::string& key) {
    if (const char* v = std::getenv(key.c_str())) return v;
    return std::nullopt;
}

// ── std::variant - type-safe union ───────────────────────────
using JsonValue = std::variant<
    std::monostate,    // null
    bool,
    int,
    double,
    std::string
>;

std::string json_to_string(const JsonValue& v) {
    return std::visit([](const auto& val) -> std::string {
        using T = std::decay_t<decltype(val)>;
        if constexpr (std::is_same_v<T, std::monostate>) return "null";
        if constexpr (std::is_same_v<T, bool>)           return val ? "true" : "false";
        if constexpr (std::is_same_v<T, std::string>)    return '"' + val + '"';
        else {
            std::ostringstream oss; oss << val;
            return oss.str();
        }
    }, v);
}

int main() {
    // ── optional ────────────────────────────────────────────
    auto a = parse_int("42");     // has value
    auto b = parse_int("hello");  // no value

    if (a) std::cout << "parsed: " << *a << "
";          // 42
    if (!b) std::cout << "parse failed for 'hello'
";

    // value_or - provide default
    std::cout << a.value_or(-1) << "
";  // 42
    std::cout << b.value_or(-1) << "
";  // -1

    // optional in map - no sentinel values needed
    std::map<std::string, std::optional<int>> settings;
    settings["timeout"] = 30;
    settings["retries"] = std::nullopt;  // configured as "no value"

    if (auto& t = settings["timeout"]; t.has_value()) {
        std::cout << "timeout=" << *t << "
";
    }

    // ── variant ────────────────────────────────────────────
    std::vector<JsonValue> values = {
        std::monostate{},    // null
        true,
        42,
        3.14,
        std::string{"hello"}
    };

    for (const auto& v : values) {
        std::cout << json_to_string(v) << "
";
        std::cout << "index=" << v.index() << "
";  // which type is active
    }

    // holds_alternative - type check
    JsonValue jv = 42;
    if (std::holds_alternative<int>(jv)) {
        std::cout << "It's an int: " << std::get<int>(jv) << "
";
    }

    // std::get throws std::bad_variant_access if wrong type
    try {
        auto s = std::get<std::string>(jv);
    } catch (const std::bad_variant_access& e) {
        std::cerr << "bad_variant_access: " << e.what() << "
";
    }

    // std::get_if - returns nullptr on type mismatch (no throw)
    if (const int* p = std::get_if<int>(&jv)) {
        std::cout << "int via get_if: " << *p << "
";
    }

    // ── Structured bindings ────────────────────────────────
    auto [quotient, remainder] = std::pair{17/5, 17%5};
    std::cout << "17/5=" << quotient << " rem=" << remainder << "
";

    std::map<std::string, int> scores{{"Alice",95},{"Bob",72}};
    for (const auto& [name, score] : scores) {
        std::cout << name << ": " << score << "
";
    }

    // Structured binding from struct
    struct Point3D { double x, y, z; };
    Point3D pt{1.0, 2.0, 3.0};
    auto [px, py, pz] = pt;
    std::cout << px << " " << py << " " << pz << "
";

    return 0;
}

Common Mistakes

  • Dereferencing an empty optional crashes - `*opt` or `opt.value()` when `opt` is empty: `value()` throws `std::bad_optional_access`; `*opt` is UB. Always check `if (opt)` or `opt.has_value()` first.
  • Modifying a variant to a different type unexpectedly - `jv = std::string{"x"}` changes the active type from `int` to `string`. Old references/pointers obtained via `std::get<int>` are now invalid. Never hold results of `get_if<T>` across variant assignments.
  • Structured bindings with references - `auto [a, b] = some_pair` copies the pair elements. Use `auto& [a, b] = some_pair` to bind references (modify the original), or `const auto& [a, b]` for read-only references.

Tip

Tip

Practice stdoptional stdvariant structured bindings in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Type-safe vocabulary types and modern unpacking syntax

Practice Task

Note

Practice Task - (1) Write a working example of stdoptional stdvariant structured bindings from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with stdoptional stdvariant structured bindings is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • `std::optional<T>` (C++17) represents a value that **may or may not exist** - a cleaner alternative to nullable pointers or sentinel values.
  • Dereferencing an empty optional crashes - `*opt` or `opt.value()` when `opt` is empty: `value()` throws `std::bad_optional_access`; `*opt` is UB. Always check `if (opt)` or `opt.has_value()` first.
  • Modifying a variant to a different type unexpectedly - `jv = std::string{"x"}` changes the active type from `int` to `string`. Old references/pointers obtained via `std::get<int>` are now invalid. Never hold results of `get_if<T>` across variant assignments.
  • Structured bindings with references - `auto [a, b] = some_pair` copies the pair elements. Use `auto& [a, b] = some_pair` to bind references (modify the original), or `const auto& [a, b]` for read-only references.

Topics in This Module

0/7 done