std::variant:
std::variant
suggest changeVariant is a replacement for raw union use. It is type-safe and knows what type it is, and it carefully constructs and destroys the objects within it when it should.
It is almost never empty: only in corner cases where replacing its content throws and it cannot back out safely does it end up being in an empty state.
It behaves somewhat like a std::tuple, and somewhat like an std::optional.
Using std::get and std::get_if is usually a bad idea. The right answer is usually std::visit, which lets you deal with every possibility right there. if constexpr can be used within the visit if you need to branch your behavior, rather than doing a sequence of runtime checks that duplicate what visit will do more efficiently.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
11Loops
14keywords
17Pointers
26std::map
29std::any
30std::variant
38File I/O
39Streams
51Unions
56Lambdas
60SFINAE
62RAII
67Sorting
84RTTI
87Scopes
102Attributes
104Profiling
107Recursion
113Header files
117Iteration
125Alignment
133Optimization
134Semaphore
136Debugging
139Mutexes
141Unit testing
142decltype
146Contributors