Two examples of C ++ template metaprogramming

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.