Skip to main content

std::variant

Brief​

std::variant<int, float> my_variant; is a variable that can hold either an int or a float, and the actual type it holds can change at runtime. Using std::variant with int and float is not all that useful, but it starts to get very interesting when we use variant to represent the different states that we could be in, or to achieve polymorphism for example: std::variant<TrackballCamera, FreeflyCamera>.


An example of using variant.
Another example of using variant.

std::variant is a very good alternative to enums because – on top of beeing a list of possible states – it can contain data.

Going further​