Templates
The first available mechanism for compile-time computation in C++ was Template Meta-Programming (TMP). Using TMP, we can store the results of operations in types, as shown in the following example of computing the factorial:
template <unsigned int N>
struct factorial {
static const unsigned int value = N * factorial<N-1>::value;
};
template <>
struct factorial<0> {
static const unsigned int value = 1;
};
int main () {
const int fact = factorial<5>::value;
return fact;
}
If you run this example in Compiler Explorer (even without optimizations), you will see that it returns 120. The generated assembly code is short and does not contain any function calls. It simply places the value 120 in the return register in the main function, meaning the factorial computation was done at compile time. You can see the generated assembly code here:
main:
push rbp
mov rbp, rsp
mov DWORD PTR [rbp...