Daily bit(e) of C++ | std::variant (basics)
Daily bit(e) of C++ ♻️64, The C++17 type-safe alternative to a union: std::variant.
The C++17 std::variant is a type-safe alternative to a union.
Unlike a union, where accessing the non-active member is undefined behaviour, a std::variant will instead throw an exception.
A std::variant will also internally handle the correct construction and destruction of non-trivial members (which otherwise would have to be handled manually).
While some tutorials present std::variant as a "type-erasure" tool, this is misleading as std::variant carries the types of members which cannot be incomplete.