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.
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.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?