How do I construct and use std::variant in C++?

In C++, std::variant is a type-safe union which can hold one of several different types at a time. It is a powerful feature that allows for more expressive code and helps manage types in a cleaner way compared to traditional unions.

Constructing and Using std::variant

To construct a std::variant, you first need to include the necessary header:

#include <variant>

You can define a variant type by specifying the types it can hold. Here’s how to create a variant that can hold either an int or a std::string:

std::variant<int, std::string> myVariant;

To assign a value to the variant, you simply assign it like you would with a normal variable:

myVariant = 10; // Holds an int
myVariant = "Hello, world!"; // Now holds a std::string

To retrieve the value stored in a variant, you can use std::get, but be mindful of the type you are retrieving. Here's an example:

if (std::holds_alternative<int>(myVariant)) {
        int value = std::get<int>(myVariant);
        std::cout << "The value is: " << value << std::endl;
    } else {
        std::string value = std::get<std::string>(myVariant);
        std::cout << "The value is: " << value << std::endl;
    }

This way, you can safely check what type is currently held in your variant before attempting to access it.


std::variant C++ type-safe union variant example C++ variant construction