June 2025
Intermediate to advanced
1093 pages
33h 24m
English
With this template, you can model something similar to a union, but in a safer form.
A union has the problem in safe programming that constructors or destructors of the contained objects are not reliably called.
A variant can take the value of one of several types. Setting a value of one type changes the state of variant, so attempting to read another type from it then fails. Thus, its usage is safe.
// https://godbolt.org/z/baY7Tz91f#include <variant>using std::get;int main() { std::variant<int, float> v{}; v = 12; // State changes to int auto i = get<int>(v); // retrieves the int std::cout << i << '\n'; // Output: 12 v = 3.456f; // State changes to float std::cout << get<float>(v) << '\n'; // Output: ...
Read now
Unlock full access