cpp / expert
Snippet
Compile-time Bounds Validation for Static Arrays
This snippet demonstrates how to use templates and static_assert to enforce array bounds checking at compile time. By using a template parameter for the index, the compiler can prevent out-of-bounds access before the code even runs, which is more efficient and safer than runtime checks.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <array>#include <stdexcept>#include <utility>template <typename T, std::size_t N>struct CheckedArray {std::array<T, N> data;template <std::size_t Index>constexpr const T& get() const {static_assert(Index < N, "Array index out of bounds!");return data[Index];}template <typename... Args>static constexpr CheckedArray create(Args&&... args) {return { {std::forward<Args>(args)...} };}};
Breakdown
1
template <typename T, std::size_t N>
Defines a template class taking a type and a constant size.
2
static_assert(Index < N, "...");
Triggers a compile error if the requested index exceeds the array size.
3
std::forward<Args>(args)...
Uses perfect forwarding to initialize the internal array with constructor arguments.