cpp / expert
Snippet
Type-Safe Algebraic Sum Types via std::variant
std::variant is a type-safe union that knows which type it currently holds. Using std::visit allows for compile-time exhaustive checking of all possible types, replacing unsafe C-style unions and complex inheritance hierarchies for simple sum types.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <variant>#include <string>#include <iostream>using Result = std::variant<int, std::string, double>;struct Visitor {void operator()(int i) const { std::cout << "Integer: " << i; }void operator()(const std::string& s) const { std::cout << "String: " << s; }void operator()(double d) const { std::cout << "Double: " << d; }};int main() {Result r = "Error 404";std::visit(Visitor{}, r);r = 42;std::visit([](auto&& arg) { std::cout << arg; }, r);}
Breakdown
1
using Result = std::variant<int, std::string, double>;
Defines a variable that can hold exactly one of the listed types safely.
2
std::visit(Visitor{}, r);
Applies the matching overload of the visitor based on the runtime type in the variant.