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