C++ std::variant vs union: Type-Safe Sum Types

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

Aspectunionstd::variant
Active type trackingManualAutomatic
Non-trivial typespainful/illegal in classic unionssupported
visitationmanual switchesstd::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::variant for sum types in modern C++
  • union for low-level/C interop only

  • optional
  • Visitor pattern

Keywords

std::variant, union, tagged union, std::visit


  • Union and variant