optional, variant & any (C++17)
Three vocabulary types retire ad-hoc missing-or-alternate encodings: std::optional<T> holds a T or nothing (replacing sentinel -1s and null outputs), std::variant<A,B> holds exactly one of its listed types (a type-safe union for heterogeneous values), and std::any holds anything with runtime-checked casts. All live in standard headers with value semantics — copyable, comparable, printable through visitors.
Use optional for possibly-absent results, variant plus std::visit for closed type sets with behavior per alternative, and any sparingly (plugin payloads, registries) where the type truly can't be enumerated.
optional: value or nothing
std::optional<int> r; empty until assigned — has_value()/operator bool test, value() or value_or(fallback) unwrap.
variant: one of these
std::variant<int, std::string> v = 42; — holds exactly one alternative; std::visit dispatches behavior per held type.
any: anything, checked
std::any a = 3.14; with std::any_cast<double>(a) — wrong casts throw bad_any_cast instead of corrupting.
Pick by knowledge
Absence → optional; known alternatives → variant; unknowable → any. Each step down trades compile-time safety for flexibility.
#include <iostream>#include <optional>#include <string> std::optional<int> parse(const std::string& s) { if (s.empty()) return std::nullopt; return (int)s.size();} int main() { std::cout << parse("hey").value_or(-1) << std::endl; std::cout << parse("").value_or(-1) << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.