Learn C++
#include "advanced/optional_variant.hpp"

optional, variant & any (C++17)

//concept

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.

//how it works
1

optional: value or nothing

std::optional<int> r; empty until assigned — has_value()/operator bool test, value() or value_or(fallback) unwrap.

2

variant: one of these

std::variant<int, std::string> v = 42; — holds exactly one alternative; std::visit dispatches behavior per held type.

3

any: anything, checked

std::any a = 3.14; with std::any_cast<double>(a) — wrong casts throw bad_any_cast instead of corrupting.

4

Pick by knowledge

Absence → optional; known alternatives → variant; unknowable → any. Each step down trades compile-time safety for flexibility.

//example
#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;
}
Output
3
-1
1Non-empty input returns an engaged optional holding the length 3.
2Empty input returns nullopt — no sentinel length, no exception, no output parameter.
3value_or(-1) unwraps or falls back, printing 3 then -1 — absence handled at the call site.
//use cases
Search and parse results that may legitimately find nothing
Heterogeneous config values with visitor-dispatched behavior
Plugin registries carrying type-erased payloads safely
Replacing -1/nullptr sentinels with compiler-checked absence

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.