## Introduction

It is possible to carry out far from trivial calculations at compile time. As a sample, in this article I will show how to calculate the area under any real function between arbitrary boundaries A and B. I will use standard and widespread algorithms, like trapezoidal rule and Simpson’s rule.

Computing at compile time means that the result of the operation is known by the time the process is loaded in memory, before entering the `main`

function.

## The magic of the main function

Have a look at this code:

#include <cmath>
#include <iostream>
#include "simpsons_rule.h"
const double PI = 4.0 * atan(1.0);
double F(double x) {return cos(x);} extern const double A = 0.0; extern const double B = PI / 2.0;
int main(int argn, char *argc[])
{
std::cout << simpsons_rule<F, A, B, 100>::result << std::endl;
return 0;
}

The program above simply displays the value stored in a static variable `result`

belonging to the class `simpsons_rule<>`

. This value is evaluated at compile time and stored in memory before `main()`

is accessed. `result`

stores the integral of cos(x) (function `F`

) between 0.0 (`A`

) and PI/2.0 (`B`

). The exact result is 1. The displayed result is also 1. Thus, the approximation is almost perfect in this case (think about round-off errors).

If you now change `F`

, `A`

or `B`

and recompile, you will get a different value for `result`

.

So this is the crux and the magic of the matter: **at runtime no computations are done**; the only performed task is displaying the result.

Note that in order to use `F`

, `A`

and `B`

as template arguments, they must have external linkage; they are globals and their values are known at compile time.

Now it is time to see the guts, but instead of diving into trapezoidal or Simpson’s rules implementations, it is much more illustrative to show a simpler (but analogous) case: the factorial.

## Implementing the factorial (1)

To compute the factorial of an integer n (noted as n!), just apply the following formula:

The following code implements the factorial computation at compile time:

#ifndef FACTORIAL_H
#define FACTORIAL_H
#include <cstddef>
template <size_t N>
struct factorial
{
static const size_t result;
};
template <size_t N>
const size_t factorial<N>::result = N * factorial<N - 1>::result;
template <>
struct factorial<1>
{
static const size_t result;
};
const size_t factorial<1>::result = 1;
#endif

If you browse in other sources (ref. [3], for example), you will probably find less verbose implementations. Please, stay with this for the moment: it will help you find resemblances to trapezoidal and Simpson’s rules implementations later.

The code above declares a class template named `factorial<>`

**[1]** and a specialization `factorial<1>`

**[3]**. In **[2]** the static unsigned integer `result`

is defined for `factorial<>`

. In **[4]** the static unsigned integer `result`

is defined for `factorial<1>`

.

Now suppose you write this sentence in the main function:

std::cout << factorial<5>::result << std::endl;

As you can see in **[2]**, the compiler resolves `factorial<5>::result`

as:

factorial<5>::result = 5 * factorial<4>::result

But also in **[2]** `factorial<4>::result`

is resolved as:

factorial<4>::result = 4 * factorial<3>::result

Following this reasoning in a recursive way we get:

factorial<5>::result = 5 * 4 * 3 * 2 * factorial<1>::result

`factorial<1>::result`

is resolved in **[4]** as 1. We get then:

factorial<5>::result = 5 * 4 * 3 * 2 * 1

The compiler finally carries out the multiplication above, and `factorial<5>::result`

is resolved at compile time as 120.

## Implementing the factorial (2)

The following code is a not so known alternative, only valid since C++11:

#ifndef FACTORIAL_H
#define FACTORIAL_H
#include <cstddef>
template <size_t N, size_t M = N + 1, size_t... Indices>
struct factorial : public factorial<N, M - 1, M – 1, Indices...> {};
template <size_t N, size_t... Indices>
struct factorial<N, 1, Indices...> {
static const size_t result;
};
template <size_t N, size_t First, size_t... Rest>
struct factorial<N, 1, First, Rest...> {
static const size_t result;
};
template <size_t N, size_t First, size_t... Rest> const size_t factorial<N, 1, First, Rest...>::result =
First * factorial<N, 1, Rest...>::result;
template <size_t N> struct factorial<N, 1>
{
static const size_t result;
};
template <size_t N> const size_t factorial<N, 1>::result = 1;
#endif

How does the compiler resolve `factorial<5>::result`

in this case? If you have a look at **[1]**, you will see that `factorial<5>`

can be resolved into `factorial<5, 5, 5>`

, being `Indices…`

an empty pack. Without taking your eyes off **[1]**, you can follow the chain:

factorial<5> -> factorial<5, 5, 5>, with Indices… empty.
factorial<5, 5, 5> -> factorial<5, 4, 4, 5>, with Indices… = {5}.
factorial<5, 4, 4, 5> -> factorial<5, 3, 3, 4, 5>, with Indices… = {4, 5}.
factorial<5, 3, 3, 4, 5> -> factorial<5, 2, 2, 3, 4, 5>, with Indices… = {3, 4, 5}.
factorial<5, 2, 2, 3, 4, 5> -> factorial<5, 1, 1, 2, 3, 4, 5>, with Indices… = {2, 3, 4, 5}.

Once the compiler gets `factorial<5, 1, 1, 2, 3, 4, 5>`

it can be resolved by the specialization at **[2]**. It becomes then `factorial<5, 1, Indices…>`

, being `Indices…`

the pack: {1, 2, 3, 4, 5}.

The technique above is very interesting because it allows us to get a pack of indices for the operands involved in our computation. In the case of the factorial, indices and operands (numbers to be multiplied) are the same, but this is just a particular case.

In **[3]** our indices pack is split in two: the first index and the rest. You can find in **[4]** the definition of `result`

for the specialization in **[3]**. It is self-explanatory.

The termination condition is reached when `Rest…`

is empty. Such case is implemented in **[5]** and **[6]**.

After following the previous steps, the compiler finally resolves `factorial<5>::result `

as 120. As you can imagine, both methodologies come together to the same binary output.

## An esoteric Fibonacci sequence

As another illustrative example, you can use the technique above to compute an element in a Fibonacci sequence. Be indulgent with me if it looks weird to your eyes:

#ifndef FIBONACCI_H
#define FIBONACCI_H
#include <cstddef>
template <
size_t SequenceSize,
size_t CurrentSequenceSize = 0,
size_t M = 1,
size_t N = 0,
size_t... Series
>
struct fibonacci :
public fibonacci<SequenceSize, CurrentSequenceSize + 1, M + N, M, N, Series...>
{};
template <size_t SequenceSize, size_t M, size_t N, size_t First, size_t... Rest>
struct fibonacci<SequenceSize, SequenceSize, M, N, First, Rest...>
{
static const size_t value;
};
template <size_t SequenceSize, size_t M, size_t N, size_t First, size_t... Rest>
const size_t fibonacci<SequenceSize, SequenceSize, M, N, First, Rest...>::value = First;
#endif

If you type (for instance) `fibonacci<5>::value`

in the `main`

function, it will be resolved as 3 (the fifth element in the series). I agree this is not the most intuitive way to compute a Fibonacci sequence, of course.

## The trapezoidal rule

Observe that factorial of n can be written schematically as:

where f(x)=x and {i_{1}, i_{2},…, i_{n}} is a collection of indices with values ranging from 1 to n.

The trapezoidal rule can be arranged into a similar pattern:

where:

In the code below, `summation<>`

class template carries out the summation of the g()’s:

#ifndef TRAPEZOIDAL_RULE_H
#define TRAPEZOIDAL_RULE_H
#include <cstddef>
typedef double (*integrand_type)(double);
typedef const double& boundary_type;
template <integrand_type F, boundary_type A, boundary_type B, size_t N, size_t I = N - 1>
struct summation
{
static const double result;
};
template <integrand_type F, boundary_type A, boundary_type B, size_t N, size_t I>
const double summation<F, A, B, N, I>::result =
F(A + I * (B - A) / N) + summation<F, A, B, N, I - 1>::result;
template <integrand_type F, boundary_type A, boundary_type B, size_t N>
struct summation<F, A, B, N, 0>
{
static const double result;
};
template <integrand_type F, boundary_type A, boundary_type B, size_t N>
const double summation<F, A, B, N, 0>::result = 0.0;
template <integrand_type F, boundary_type A, boundary_type B, size_t N>
struct trapezoidal_rule
{
static const double result;
};
template <integrand_type F, boundary_type A, boundary_type B, size_t N>
const double trapezoidal_rule<F, A, B, N>::result =
(B - A) / N * (0.5 * (F(A) + F(B)) + summation<F, A, B, N>::result);
#endif

The code above bears resemblance to the first implementation of factorial. If you look for resemblance to the second implementation, here you are the code:

#ifndef TRAPEZOIDAL_RULE_2_H
#define TRAPEZOIDAL_RULE_2_H
#include <cstddef>
typedef double (*integrand_type)(double);
typedef const double& boundary_type;
template <integrand_type F, boundary_type A, boundary_type B, size_t N, size_t M = N, size_t... Indices>
struct summation_ : public summation_<F, A, B, N, M - 1, M - 1, Indices...> {};
template <integrand_type F, boundary_type A, boundary_type B, size_t N, size_t... Indices>
struct summation_<F, A, B, N, 1, Indices...> {
static const double result;
};
template <integrand_type F, boundary_type A, boundary_type B, size_t N, size_t First, size_t... Rest>
struct summation_<F, A, B, N, 1, First, Rest...> {
static const double result;
};
template <integrand_type F, boundary_type A, boundary_type B, size_t N, size_t First, size_t... Rest>
const double summation_<F, A, B, N, 1, First, Rest...>::result =
F(A + First * (B - A) / N) + summation_<F, A, B, N, 1, Rest...>::result;
template <integrand_type F, boundary_type A, boundary_type B, size_t N>
struct summation_<F, A, B, N, 1>
{
static const double result;
};
template <integrand_type F, boundary_type A, boundary_type B, size_t N>
const double summation_<F, A, B, N, 1>::result = 0.0;
template <integrand_type F, boundary_type A, boundary_type B, size_t N>
struct trapezoidal_rule_2
{
static const double result;
};
template <integrand_type F, boundary_type A, boundary_type B, size_t N>
const double trapezoidal_rule_2<F, A, B, N>::result =
(B - A) / N * (0.5 * (F(A) + F(B)) + summation_<F, A, B, N>::result);
#endif

Once we have understood both factorial implementations, I think these two last pieces of code are clear, well commented and self-explanatory.

The implementation for Simpson’s rule (a more precise integration method) follows the same ideas but it is a little more verbose, because it arises from a bit more complicated formula. You can find it in the enclosed zip.

## Source code

The trapezoidal and Simpson’s rules implementation code has been attached, along with a main sample code. The code has been written with Code::Blocks and compiled with MinGw (mingw-get-inst-20120426).

## References

- Trapezoidal rule. (http://en.wikipedia.org/wiki/Trapezoidal_rule).
- Simpson’s rule. (http://en.wikipedia.org/wiki/Simpson's_rule).
- Compile time function execution. (http://en.wikipedia.org/wiki/Compile_time_function_execution).
- “Unpacking” a tuple to call a matching function pointer. (http://stackoverflow.com/questions/7858817/unpacking-a-tuple-to-call-a-matching-function-pointer).