C ++ template metaprogramming is a mechanism that uses templates for computation during the compilation period. It can be considered as a programming method of C ++.
Example 1: Calculate the factorial of integer n.
// The general form of the template <int n> class factorial {public: Enum {_ result = N * factorial <N-1 >:: _ result };}; // special template used to end recursive rules <> class factorial <0 >{ public: Enum {_ result = 1 };}; int main () {const int num = 10; cout <num <"! = "<Factorial <num >:_ result <Endl ;}
Running result: 10! = 3628800
I think the method of thinking is the application of mathematical induction. Note the role of the template. During the compilation period, the compiler uses the template to generate the class factorial <0> ...... Class factorial <10> has a total of 11 class definitions. When the program is running, the computing process does not take up CPU time, but so many class definitions occupy some memory.
Example 2: If statement during compilation
This is an example of Bjarne stroustrup in evolving a language in and for the real world C ++ 1991-2006.
struct T_Left{ int value;};struct T_Right{ char value;};template<bool b, class X, class Y>struct if_{ typedef X type; // use X if b is true};template<class X, class Y>struct if_<false, X, Y>{ typedef Y type; // use Y if b is false};int main(){ cout << "Type Size = " << sizeof(if_<sizeof(T_Left) < 4, T_Left, T_Right>::type) << endl;}
In fact, it is also based on the value that can be determined during the compilation period to choose the compilation period.
The Application of template metaprogramming includes blitz ++ library, boost: MPL library, and typelist mentioned in modern c ++ design.