0 day streak
cpp / intermediate
Snippet

Type-Safe Variant Selection

std::variant provides a type-safe alternative to unions. Combined with std::visit, it allows for branching logic that respects the specific type currently stored.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <variant>
#include <string>
int main() {
std::variant<int, std::string> data = "C++ Standard";
// std::visit handles the control flow based on the active type
std::visit([](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, int>) {
std::cout << "Integer: " << arg << std::endl;
} else if constexpr (std::is_same_v<T, std::string>) {
std::cout << "String: " << arg << std::endl;
}
}, data);
return 0;
}
Breakdown
1
std::variant<int, std::string> data = ...
Declares a variable that can hold either an integer or a string safely.
2
if constexpr (std::is_same_v<T, int>)
A compile-time conditional check to determine the type of the visitor's argument.