C + + template meta-programming three: cyclic expansion

Source: Internet
Author: User

2.2Loop unrolling Looping expansion

The previous enum section describes the combination with the template, which throws a magical effect on the compiler recursion. The template itself can achieve recursive results without the need for enum mates.

Test template recursive for loop unrolling    cout << ' test 2:template recursive for Loop unrolling ' << E NDL;    for (size_t i = 0; i < 8; ++i) {      cout << i;    }    cout << Endl;    Loop<8>::run ();    cout << Endl;

The output is:

Test 2:template recursive for Loop unrolling0123456701234567

To achieve the above simulation for loop effect, you need to define a loop class:

Template<int N>class Loop {public:  static inline int Run () {    int v = loop<n-1>::run ();    cout << v;    return v + 1;  }}; Template<>class loop<0> {public:  static inline int Run () {    return 0;  }};

This shows how the for loop expands, because there is no recursion and looping in the compiled code. Some are a lot of special class Loop<8>, Loop<7> The run () method is executed by the loop<0>. Execute code similar to the following:

Loop<8>::run (); Loop<7>::run (); Loop<6>::run ();.. Loop<0>::run ();

C + + template meta-programming three: cyclic expansion

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.