Header Reference: <optional>
Header Reference: <optional>
The main type, operations, and usage patterns around std::optional and optional-style APIs.
Header Reference: <optional>
The main type, operations, and usage patterns around std::optional and optional-style APIs.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
Header reference pages are meant to answer a practical question quickly: what this header provides, when to reach for it, and which usage rules are easiest to get wrong.
<optional>std::optional<T>std::nullopthas_value(), value(), and value_or()std::expectedstd::variant#include <optional>
#include <string_view>
std::optional<int> parse_count(std::string_view text) {
if (text.empty()) {
return std::nullopt;
}
return 3;
}
This is the right optional shape: either a meaningful value is present or it is not. There is no richer failure payload, and callers can branch on presence directly.
std::optional<T> when absence is ordinary and no detailed error reason is neededvalue_or() for simple fallback behavior and has_value() or if (opt) for branchingstd::expected<T, E> when callers need to know why the value is absent#include <optional>
#include <string>
std::optional<std::string> lookup(bool found) {
if (!found) {
return std::nullopt;
}
return "value";
}