std::variant là type-safe union — tại một thời điểm chỉ giữ một giá trị, nhưng luôn biết kiểu đang giữ là gì.
cpp
std::variant<int, double, std::string> v;
v = 42; // giữ int
v = 3.14; // giữ double
v = "hello"; // giữ string
// Truy cập:
std::cout << std::get<double>(v); // OK
// std::get<int>(v); // throw std::bad_variant_access
// Pattern matching:
std::visit([](auto&& val) {
std::cout << val;
}, v);Khác union:
union | std::variant | |
|---|---|---|
| Type tracking | Không | Có |
| Destructor | Không tự gọi | Tự gọi |
| An toàn | Không (UB nếu đọc sai kiểu) | An toàn |
Dùng khi: cần lưu một trong nhiều kiểu (kết quả parse, AST node, lỗi/giá trị).
std::variant is a type-safe union — holds one value at a time, but always knows which type it is currently holding.
cpp
std::variant<int, double, std::string> v;
v = 42; // holds int
v = 3.14; // holds double
v = "hello"; // holds string
// Access:
std::cout << std::get<double>(v); // OK
// std::get<int>(v); // throws std::bad_variant_access
// Pattern matching:
std::visit([](auto&& val) {
std::cout << val;
}, v);vs union:
union | std::variant | |
|---|---|---|
| Type tracking | No | Yes |
| Destructor | Not called automatically | Called automatically |
| Safety | No (UB if wrong type read) | Safe |
Use when: you need to store one of several types (parse results, AST nodes, error-or-value patterns).