Store Different Types with std::variant
Learn to store different types with std::variant.
Introduced with C++17, the std::variant
class may hold different values, one at a time, where each value must fit in the same allocated memory space. It's useful for holding alternative types for use in a single context.
Differences from the primitive union structure
The variant
class is a union
structure in that only one type may be in effect at a time. The primitive union
type, inherited from C, is a structure where the same datum may be accessed as different types. For example:
union ipv4 {struct {uint8_t a; uint8_t b; uint8_t c; uint8_t d;} quad;uint32_t int32;} addr;addr.int32 = 0x2A05A8C0;cout << format("ip addr dotted quad: {}.{}.{}.{}\n", addr.quad.a, addr.quad.b, addr.quad.c, addr.quad.d);cout << format("ip addr int32 (LE): {:08X}\n", addr.int32);
Output:
ip addr dotted quad: 192.168.5.42ip addr int32 (LE): 2A05A8C0
In this example, the union
has two members, types struct
and uint32_t
, where struct
has four uint8_t
members. This gives us two different ...
Get hands-on with 1400+ tech skills courses.