std::optional, std::variant, and std::any in C++
Learn std::optional, std::variant, and std::any in C++ to write safer, more flexible, and expressive modern C++ applications.
Modern C++ (C++17 and later) provides three powerful tools for representing data types more safely and flexibly: std::optional, std::variant, and std::any. These utilities significantly reduce the need for raw pointers or manual handling of ambiguous data types.
In this article, we examine each structure individually, explain their usage, and show best practices with practical examples.
1) std::optional — A Value That May or May Not Exist
std::optional safely represents variables that may contain a value or be empty. It is a modern, safer alternative to using null pointers.
Basic usage:
optional<int> number;
number = 42;
if (number.has_value()) {
cout << "Value: " << number.value() << endl;
}
Providing a default value with value_or:
optional<string> name;
cout << name.value_or("No name");
Returning optional from a function:
optional<int> add(int a, int b, bool enabled) {
if (!enabled)
return nullopt;
return a + b;
}
2) std::variant — One of Several Possible Types
std::variant allows a variable to hold exactly one of several predefined types. It acts as a type-safe alternative to unions.
Basic definition:
variant<int, double, string> data;
data = 10;
data = 3.14;
data = string("Hello");
Accessing the stored value with get:
variant<int, string> v = 25;
cout << get<0>(v); // int
Safe access using get_if:
if (auto p = get_if<string>(&v)) {
cout << "String: " << *p;
}
Using a visitor to process all possible types:
variant<int, double, string> data = 3.14;
visit([](auto& val) {
cout << "Value: " << val;
}, data);
3) std::any — Store Any Type
std::any can store an object of any type. However, it is less type-safe compared to std::variant, since type information is erased internally.
It essentially represents a “container for any type.”
Basic usage:
any value;
value = 10;
value = string("Hello");
Extracting data using any_cast:
any data = 42;
try {
int n = any_cast<int>(data);
cout << n;
} catch (const bad_any_cast& e) {
cout << "Bad any_cast!";
}
Flexible function parameters:
void print(const any& a) {
if (a.type() == typeid(int))
cout << any_cast<int>(a);
else if (a.type() == typeid(string))
cout << any_cast<string>(a);
}
4) optional vs variant vs any — When to Use What?
| Utility | Use Case | Advantage |
|---|---|---|
| std::optional | “May have a value or not.” | Lightweight, safe alternative to null |
| std::variant | One of several defined types | Strong type safety |
| std::any | Type is unknown or highly dynamic | Most flexible |
5) Performance Notes
- optional is very lightweight — near-zero overhead
- variant has strong type guarantees but a small runtime overhead
- any is the most expensive — uses dynamic allocation and type erasure
6) TL;DR
- optional: for “value may exist” scenarios
- variant: for “one of several types” cases
- any: for completely dynamic types
- All introduced in C++17 — widely used in modern C++
- Compatible with Visual Studio 2022, GCC, and Clang