Template metaprogramming: Difference between revisions

Content deleted Content added
m linking
Line 23:
What exactly "programming at compile-time" means can be illustrated with an example of a factorial function, which in non-template C++ can be written using recursion as follows:
<syntaxhighlight lang=cpp>
unsigned int factorial(unsigned int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
Line 34:
By using template metaprogramming and template specialization to provide the ending condition for the recursion, the factorials used in the program—ignoring any factorial not used—can be calculated at compile time by this code:
<syntaxhighlight lang=cpp>
template <unsigned int nN>
struct factorial {
enumstatic {constexpr unsigned value = nN * factorial<nN - 1>::value };
};
 
template <>
struct factorial<0> {
enumstatic {constexpr unsigned value = 1 };
};