cpp / expert
Snippet
Kompilierzeit-Typ-Dispatching für Variant-Typen
Nutzung des Visitor-Patterns zur typsicheren Inspektion von Summentypen (Variants). Dies bietet eine robuste Alternative zu manuellen Typ-Checks und Casts.
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);}
Erklärung
1
using Payload = std::variant<int, double>;
Definiert eine typsichere Union, die entweder einen int oder einen double halten kann.
2
void operator()(int i)
Überladener Aufrufoperator zur Behandlung des spezifischen Typs im Variant.
3
std::visit(Processor{}, p);
Dispatcher, der den richtigen Overload basierend auf dem Laufzeittyp von p aufruft.