0 day streak
cpp / expert
Snippet

Algebraic Pattern Matching with Type-Safe Visitors

This snippet uses the 'overload' pattern to implement algebraic pattern matching in C++. It combines variadic inheritance and deduction guides to create a type-safe visitor for std::variant, enabling complex control flow based on variant data types.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <variant>
#include <string>
template<class... Ts> struct overload : Ts... { using Ts::operator()...; };
template<class... Ts> overload(Ts...) -> overload<Ts...>;
using State = std::variant<int, std::string, bool>;
void dispatch(const State& s) {
std::visit(overload {
[](int i) { /* Control flow for integer */ },
[](const std::string& s) { /* Control flow for string */ },
[](bool b) { /* Control flow for boolean */ }
}, s);
}
Breakdown
1
template<class... Ts> struct overload : Ts... { using Ts::operator()...; };
Uses variadic inheritance to aggregate multiple lambda function call operators into a single type.
2
std::visit(overload { ... }, s);
Dispatches execution to the appropriate lambda based on the active type stored in the variant at runtime.