Introduction to std::variant

A type-safe union in C++17

4 min readFeb 12, 2024

Prior to C++17, programmers could define a union, a data type that allows you to define members of different types where the members share the same memory location. This is advantageous in situations like the following:

#include <iostream>

union Record {
int intValue;
float floatValue;

int main() {
Record record1;
record1.intValue = 10;
std::cout << "Integer value: " << record1.intValue << std::endl;

Record record2;
record2.floatValue = 10.5;
std::cout << "Float value: " << record2.floatValue << std::endl;

return 0;

In this example, the Record type allows you to store either an int value or a float value in the same memory location. This may represent some type of record in a database where each record could be one of the two possible types. If you needed to store multiple values in a data structure at the same time, then a struct would be a more appropriate choice than a union.

The problem with unions is that they are not type-safe. As a programmer, you need to know what type the union holds, otherwise you will get garbage data. Consider the following example using the Record union from above:

int main() {
Record record;
record.intValue = 10;

float val = record.floatValue;
std::cout << "val: " << val << std::endl;

return 0;
val: 1.4013e-44

Here, the intValue field of the Record union is set, so the intended type for this…




Software engineer specializing in operating systems, navigating the intracicies of the C++ language and systems programming.