0 day streak
cpp / intermediate
Snippet

Polymorphic Value Storage via Type-Safe Unions

std::variant is a type-safe union that can hold one of several specified types. Unlike traditional C-style unions, it knows which type it currently holds and ensures type safety via exceptions or safe access pointers.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <variant>
#include <string>
#include <iostream>
void process_input() {
std::variant<int, std::string> value;
value = 10;
if (std::holds_alternative<int>(value)) {
std::cout << "Int: " << std::get<int>(value) << "\n";
}
value = "Modern C++";
// Using get_if to avoid exceptions
if (auto* s = std::get_if<std::string>(&value)) {
std::cout << "String: " << *s << "\n";
}
}
Breakdown
1
std::variant<int, std::string> value;
Declares a variable that can be either an int or a string.
2
std::get_if<std::string>(&value)
Returns a pointer to the string if active, otherwise nullptr.