0 Tage Serie
cpp / expert
Snippet

Verzweigungsfreier Dispatch via Funktionszeiger-Tabellen

Optimierung des Multi-Way-Kontrollflusses durch direktes Mapping von Enumerationswerten auf eine Lookup-Tabelle, wodurch bedingte Verzweigungen und Pipeline-Stalls eliminiert werden.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
enum class Cmd { Start, Stop, Reset };
void onStart() {}
void onStop() {}
void onReset() {}
using Action = void(*)();
static constexpr Action dispatch[] = { onStart, onStop, onReset };
void execute(Cmd cmd) {
dispatch[static_cast<int>(cmd)]();
}
Erklärung
1
using Action = void(*)();
Definiert einen Funktionszeigertyp für die Dispatch-Tabelle.
2
static constexpr Action dispatch[]
Ein zur Kompilierzeit konstantes Array, das Funktionsadressen speichert.
3
dispatch[static_cast<int>(cmd)]();
Führt einen O(1)-Sprung zur Ziellogik ohne 'if' oder 'switch' aus.