What is variant in C++: Simple Explanation and Example
std::variant in C++ is a type-safe container that can hold one value from a set of specified types at a time. It works like a box that can store different types but only one type at once, ensuring safe access to the stored value.How It Works
std::variant is like a special box that can hold one item, but that item can be one of several different types you choose. Imagine you have a box that can hold either an apple, an orange, or a banana, but only one fruit at a time. You can put any one of these fruits in the box, but not two at once.
When you use std::variant, you tell it all the possible types it can hold. Then, at any moment, it stores exactly one value of one of those types. You can check which type it currently holds and safely get the value without guessing or risking errors.
This helps avoid mistakes common with older ways of storing different types in the same place, like using raw pointers or unions without safety checks.
Example
This example shows how to create a std::variant that can hold either an int, a double, or a std::string. It stores a value, checks the type, and prints it.
#include <iostream> #include <variant> #include <string> int main() { std::variant<int, double, std::string> data; data = 42; // store int std::cout << "Integer stored: " << std::get<int>(data) << "\n"; data = 3.14; // store double std::cout << "Double stored: " << std::get<double>(data) << "\n"; data = "hello"; // store string std::cout << "String stored: " << std::get<std::string>(data) << "\n"; return 0; }
When to Use
Use std::variant when you want a variable that can hold different types but only one at a time, and you want to keep your code safe and clear. It is useful when you have data that can come in different forms, like a number or text, and you want to handle each case properly.
For example, it is great in situations like:
- Parsing data that can be multiple types (e.g., a number or a string).
- Implementing simple state machines where states hold different data.
- Replacing unsafe unions or void pointers with a safer alternative.
Key Points
std::variantholds exactly one value from a set of types.- It provides type-safe access to the stored value.
- It helps avoid errors common with unions or raw pointers.
- Use
std::get<Type>(variant)to access the value safely. - It requires C++17 or later.
Key Takeaways
std::variant safely stores one value from multiple possible types.std::variant.std::get<Type> or check type with std::holds_alternative<Type>.