0 day streak
cpp / expert
Snippet

Branchless Dispatch via Function Pointer Tables

Optimizing multi-way control flow by mapping enumeration values directly to a lookup table, eliminating conditional branching overhead and pipeline stalls.

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)]();
}
Breakdown
1
using Action = void(*)();
Defines a function pointer type for the dispatch table.
2
static constexpr Action dispatch[]
A compile-time constant array storing function addresses.
3
dispatch[static_cast<int>(cmd)]();
Performs O(1) jump to the target logic without 'if' or 'switch'.