template <unsigned N, unsigned Div> struct PrimeTest {
static const bool result = (N % Div != 0) && PrimeTest<N, Div + 1>::result;
};
template <unsigned N> struct PrimeTest<N, N> { // end
static const bool result = true;
};
template <unsigned N> struct IsPrime {
static const bool result = PrimeTest<N, 2>::result;
};
template <> struct IsPrime<1u> {
static const bool result = false;
};
static_assert(IsPrime<197>::result); // 197 is a prime
static_assert(!IsPrime<42>::result); // 42 is not
When performing computations in physics, the correctness in dimensions is important.
double mass = getMass();
double acceleration = getAcc();
double force = mass + acceleration; // Ooops! A mistake here!
Can we avoid such mistakes in compile-time? That is, to make mistakes in dimensions a compile error.
Each of the seven basic quantities corresponds to a template parameter:
template <int mass, int length, int time, int charge,
int temperature, int intensity, int amount_of_substance>
struct quantity { /* ... */ };
using mass = quantity<1, 0, 0, 0, 0, 0, 0>;
using force = quantity<1, 1, -2, 0, 0, 0, 0>;
using pressure = quantity<1, -1, -2, 0, 0, 0, 0>;
using acceleration = quantity<0, 1, -2, 0, 0, 0, 0, 0>;
mass m = getMass();
acceleration a = getAcc();
force f = m + a; // Error! No match operator+ for 'mass' and 'acceleration'!
force f = m * a; // Correct.
If the arithmetic operations of different quantitys are defined correctly, we can avoid dimension mistakes in compile-time!
Template metaprogramming is a very special and powerful technique that makes use of the compile-time computation of C++ compilers. (It is Turing-complete and pure functional programming.)
Learn a little bit more in recitations.
In modern C++, there are many more things that facilitate compile-time computations: constexpr, consteval, constinit, concept, requires, ...
Template specialization
Variadic template example: A print function.
pack...: pack expansion.sizeof...(pack) returns the number of arguments in a parameter pack. It is compile-time evaluated.if constexpr: compile-time if: compile statements conditioned on a compile-time boolean expression.Curiously Recurring Template Pattern (CRTP)
X inherit from Base<X>.Template metaprogramming (TMP)