The derivation of templates in C + + is done by the compiler at compile time, so you can use templates to programmatically implement recursive algorithms that are known to be recursive in advance to compile time from run-time to compilation. The recursive algorithm using the template is the same as the recursive algorithm of the usual pattern, which requires the recursive formula and the end condition of recursion. In template meta-programming, recursive formulas are implemented using nested dependencies of template parameters, and recursive end conditions are implemented using special template parameters. For example, for the sum of 1 to N, the formula for recursion is sums (n) = SUM (n-1) + N, and the end condition of recursion is sum (0) =0. So, we can write the following template:
#include <iostream>Template<intN>classSum { Public: enum{sum = sum<n-1>::sum +N}; };template<>classsum<0>{ Public: enum{sum =0}; };intMain () {std::cout<<"sum of 1 to:"<< sum< ->::sum <<Std::endl; return 0;}
As you can see, the first Class definition template <int n> class Sum defines a main template class for the calculation of the recursive formula, and the second template class, Template<>, Class sum<0>, is a special template class That indicates the behavior of the template class at n=0. It is important to note that the definition of a special template class must be behind the main template class. (If the class sum<n> is undefined, how does the compiler know what sum<0> is?) )
It is also important to note that the member sum in the template class here we use the enumeration type, because if you use a variable, it is not going to deduce the value at compile time (C + + class member variable initialization cannot be placed in the class definition), of course, using the static variable is also possible. Compile run Result:
Look at the compiled program binary code can be found that 5050 (binary 13BA) is directly in the form of constants into the main function, that is, the value is compiled at the time of the compiler has been calculated, in this case, the run time will be greatly reduced.
Recursive learning of C + + templates