C++ Language/Type/Variant/TemplatedVariant
A variable xVar
whose type is std::variant<int,float,std::string>
can store a value that is either int
or float
or std::string
(only one of those options at a time).
Thus, this templated-variant variable is a modern alternative to a C union
.
After assigning xVar = 9.9F;
, you know that the variable is currently storing a float
because std::holds_alternative<float>(xVar)
returns true
and xVar.index()
returns 1
(0-based indexing of type options).
Access that value by either std::get<float>(xVar)
or by std::get<1>(xVar)
.
Additional information about templated-variant (includes interactive examples)