C++ std::variant vs union: Type-Safe Sum Types
이 글의 핵심
variant vs union: safety, constructors, visitation with std::visit, and migration guidance.
std::visit and visitors pair naturally with variant; see the Visitor pattern.
Introduction: “I want to store one of several types”
union is unsafe if you read the wrong member. std::variant (C++17) is a tagged union with value semantics.
This article covers:
- Safety
std::visit- Performance notes
Comparison
| Aspect | union | std::variant |
|---|---|---|
| Active type tracking | Manual | Automatic |
| Non-trivial types | painful/illegal in classic unions | supported |
| visitation | manual switches | std::visit |
Type safety
std::get / std::get_if / std::visit help prevent reading the wrong type.
Visitor pattern
Use std::visit with an overloaded callable set for clean type dispatch.
Performance
Often similar for small alternatives; variant adds a discriminator + padding.
Summary
- Default to
std::variantfor sum types in modern C++ - union for low-level/C interop only
Related reading
- optional
- Visitor pattern
Keywords
std::variant, union, tagged union, std::visit
Related posts
- Union and variant