0 day streak
cpp / intermediate
Snippet

Type-Safe Sum Types with Variant

std::variant is a type-safe union introduced in C++17. Unlike traditional C-style unions, it knows which type it currently holds and works with std::visit to provide compile-time safety when accessing the value.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <variant>
#include <string>
int main() {
std::variant<int, std::string> data;
data = "Gemini";
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;
Defines a variable that can safely hold either an integer or a string.
2
std::visit([](auto&& arg) { ... }, data);
Applies a lambda function to the active member of the variant in a type-safe way.