Utility Types & Structured Bindings in C++

From the C++ cheat sheet · Modern C++ (C++20/23) · verified Jul 2026

Utility Types & Structured Bindings

optional, variant, and destructuring.

cpp
// Quick Reference
#include <optional>
std::optional<int> find();
if (auto r = find()) use(*r);

auto [a, b] = std::pair{1, 2};   // structured bindings
💡 std::optional expresses "maybe a value" without null pointers or magic sentinels.
⚡ .value_or(fallback) reads an optional safely; *opt / .value() throw or UB if empty.
📌 std::variant is a type-safe tagged union; access it with std::visit or std::get.
🟢 Structured bindings (auto [a, b] = ...) destructure pairs, tuples, and simple structs.
optionalvariantstructured-bindings

More C++ tasks

Back to the full C++ cheat sheet