cpp / expert
Snippet
Algebraic Data Types for Robust Control Flow
Using std::variant and std::visit allows for type-safe branching without the overhead of inheritance or the risks of C-style unions. It forces the developer to handle different data states explicitly, creating a more predictable control flow.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <variant>#include <iostream>#include <string>struct Success { std::string data; };struct Failure { int errorCode; };using Result = std::variant<Success, Failure>;void handleResult(const Result& res) {std::visit([](auto&& arg) {using T = std::decay_t<decltype(arg)>;if constexpr (std::is_same_v<T, Success>)std::cout << "OK: " << arg.data << std::endl;else if constexpr (std::is_same_v<T, Failure>)std::cout << "Error: " << arg.errorCode << std::endl;}, res);}
Breakdown
1
using Result = std::variant<Success, Failure>;
Creates a sum type that can hold either a Success or a Failure object.
2
std::visit([](auto&& arg) { ... }, res);
Applies a lambda function to the current active type in the variant.
3
if constexpr (std::is_same_v<T, Success>)
Performs compile-time type checking to execute the correct logic branch.