Modern C++ • C++20 baseline
std::optional and std::variant for Explicit States
Represent absence or one-of-many alternatives in types instead of using magic values.
std::optional<T> represents either a T or no value. std::variant<Ts...> represents one active alternative from a closed set. These types make state visible to callers, but access still requires checking or visitation; do not call value() without a reason to know it is engaged.
Key points
- optional is useful when “no result” is a normal outcome.
- variant is useful for a finite set of distinct result forms.
Example
#include <iostream>
#include <optional>
#include <string>
std::optional<int> find_code(const std::string& name) {
if (name == "ready") {
return 200;
}
return std::nullopt;
}
int main() {
if (const auto code = find_code("ready")) {
std::cout << *code << '\n';
}
}
What to expect
200
Practice exercise
Return std::nullopt for a missing lookup and add a caller branch that handles absence.
Key idea: Make ordinary alternatives explicit in the return type.