cpp / expert
Snippet
Compile-Time Type Dispatching for Variant Types
Utilizing the visitor pattern for type-safe inspection of sum types (variants). This provides a robust alternative to manual type-checking and casting.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <variant>#include <iostream>using Payload = std::variant<int, double>;struct Processor {void operator()(int i) { std::cout << "Int: " << i; }void operator()(double d) { std::cout << "Double: " << d; }};void run(Payload p) {std::visit(Processor{}, p);}
Breakdown
1
using Payload = std::variant<int, double>;
Defines a type-safe union that can hold either an int or a double.
2
void operator()(int i)
Overloaded call operator to handle the specific type within the variant.
3
std::visit(Processor{}, p);
Dispatcher that calls the correct overload based on the runtime type of p.