std::variant (C++)

The class template std::variant represents a type-safe union.

Resources

It’s a great alternative to using std::union and std::any because it provides better type safety and ease of use.

#include <variant>
std::variant<int, float, std::string> myVariant;
myVariant = 10;
 
// Access the value using std::get
std::cout << "The value is: " << std::get<int>(myVariant) << "\n";
 
// Assign a string value to the variant
myVariant = std::string("Hello, variant!");
 
// Access the string value
std::cout << "The value is: " << std::get<std::string>(myVariant) << "\n";
 
// Handling exceptions: try to access the wrong type
try {
    std::cout << "Attempting to access an int: " << std::get<int>(myVariant) << "\n";
} catch (const std::bad_variant_access& e) {
    std::cout << "Exception: " << e.what() << "\n";
}