C++ has three major ways to write compile-time computations. Those are templates,
constexpr objects and functions evaluated as part of a constant expression, and the C preprocessor. (Parts of) programs written using those techniques are called "meta-programs".
The best way (that I know of) to conceptualize metaprograms are as
programs that write code for you.
While the problem that OP poses doesn't make a lot of sense by itself (I don't know what this is needed for), we might imagine there's a bunch of
hand-written arrays scattered all around his codebase:
1 2 3 4
|
constexpr int a[5] = { 6, 7, 8, 9, 10 };
constexpr int b[10] = { -2, -1, 0, 1, 2, 3, 4, 5, 6, 7 };
constexpr int c[1] = { 42 };
// ...etc
|
If we assume that those arrays are actually necessary, then we've found a good candidate for automation. Writing all those arrays out by hand, especially the ones with a few thousand elements, is tedious at best, and a source of errors at worst.
We can have the compiler write that code for us. Notice that the compiler optimizer generates the same code whether we hand-code the array or call the
constexpr function above:
https://godbolt.org/z/KFifue
In general, we might reach for compile-time computation either to
a.) eliminate boilerplate, code duplication, and facilitate better error-checking; or, more rarely, to
b.) have the compiler do something that would otherwise happen at runtime.
If our compiler's optimizer was
impossibly perfect, we'd never need to consider point b, because the compiler would emit optimal code without our help. In practice, the optimizer can only make the simplest transformations on its own, and needs human help for anything more complicated.