cpp / expert
Snippet
Static Multidimensional Offsets
Expert level array indexing using variadic templates and fold expressions. This allows for compile-time calculation of flat offsets in a multidimensional space while maintaining a clean syntax.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
template <size_t... Dims>struct MultiArray {static constexpr size_t total_size = (Dims * ...);int data[total_size];template <typename... Indices>constexpr int& operator()(Indices... idxs) {static_assert(sizeof...(Indices) == sizeof...(Dims), "Dimension mismatch");return data[calculate_offset<0>(idxs...)];}private:template <size_t I, typename First, typename... Rest>constexpr size_t calculate_offset(First f, Rest... r) {constexpr size_t stride = get_stride<I + 1>();return (f * stride) + (sizeof...(Rest) > 0 ? calculate_offset<I + 1>(r...) : 0);}template <size_t I>static constexpr size_t get_stride() {size_t dims[] = {Dims...};size_t s = 1;for (size_t j = I; j < sizeof...(Dims); ++j) s *= dims[j];return s;}};
Breakdown
1
static constexpr size_t total_size = (Dims * ...);
Uses a C++17 fold expression to calculate the total required size of the flat array at compile time.
2
static_assert(sizeof...(Indices) == sizeof...(Dims), ...);
Ensures that the number of provided indices exactly matches the defined dimensions of the array.