0 day streak
cpp / expert
Snippet

Template-Based Loop Unrolling

This technique uses variadic templates and fold expressions to expand a loop into a sequence of function calls at compile-time. This eliminates branch overhead in performance-critical code.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <utility>
template <size_t... Is, typename F>
void static_for(std::index_sequence<Is...>, F&& func) {
(func(std::integral_constant<size_t, Is>{}), ...);
}
template <size_t N, typename F>
void unroll(F&& func) {
static_for(std::make_index_sequence<N>{}, std::forward<F>(func));
}
int main() {
unroll<4>([](auto i) {
std::cout << "Static index: " << i << "\n";
});
}
Breakdown
1
std::index_sequence<Is...>
A compile-time list of integers used to drive the expansion of the template pack.
2
(func(std::integral_constant<size_t, Is>{}), ...);
A fold expression that invokes the lambda for each index in the sequence sequentially.