Let's take a look at an example:
#include <stdio.h>
template <int depth>
class Fibnacci
{
public:
static const int value = Fibnacci<depth-1>::value + Fibnacci<depth-2>::value;
};
template <>
class Fibnacci<0>
{
public:
static const int value = 0;
};
template <>
class Fibnacci<1>
{
public:
static const int value = 1;
};
template <int depth>
void printFibnacci()
{
printFibnacci<depth-1>();
wprintf(L"%d\n", Fibnacci<depth>::value);
}
template <>
void printFibnacci<0>()
{
wprintf(L"%d\n", Fibnacci<0>::value);
}
int main()
{
printFibnacci<8>();
return 0;
}
Fibnacci series, I believe it is a programmer can write out, the point is, this fibnacci sequence of calculation is complete at compile time! The following print is also true, and when you make a large parameter, the runtime will not change, but you will spend a long time in the compile phase.
If you've heard of some template metaprogramming, you'll know that "C + + templates are Turing complete." How is the template element Turing complete? The answer is that the template element is the same as the functional principle.
The essence of a template is defined and replaced, and the essence of a lambda function is also defined and replaced, where the substitution actually conforms to the lambda calculus Theory in Mathematics: