Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For a C++ program, you can unroll loops within the language. You won't need to figure out compiler-specific options. For example,</p> <pre><code>#include &lt;cstddef&gt; #include &lt;iostream&gt; template&lt;std::size_t N, typename FunctionType, std::size_t I&gt; class repeat_t { public: repeat_t(FunctionType function) : function_(function) {} FunctionType operator()() { function_(I); return repeat_t&lt;N,FunctionType,I+1&gt;(function_)(); } private: FunctionType function_; }; template&lt;std::size_t N, typename FunctionType&gt; class repeat_t&lt;N,FunctionType,N&gt; { public: repeat_t(FunctionType function) : function_(function) {} FunctionType operator()() { return function_; } private: FunctionType function_; }; template&lt;std::size_t N, typename FunctionType&gt; repeat_t&lt;N,FunctionType,0&gt; repeat(FunctionType function) { return repeat_t&lt;N,FunctionType,0&gt;(function); } void loop_function(std::size_t index) { std::cout &lt;&lt; index &lt;&lt; std::endl; } int main(int argc, char** argv) { repeat&lt;10&gt;(loop_function)(); return 0; } </code></pre> <p><strong>Example with complicated loop function</strong></p> <pre><code>template&lt;typename T, T V1&gt; struct sum_t { sum_t(T v2) : v2_(v2) {} void operator()(std::size_t) { v2_ += V1; } T result() const { return v2_; } private: T v2_; }; int main(int argc, char* argv[]) { typedef sum_t&lt;int,2&gt; add_two; std::cout &lt;&lt; repeat&lt;4&gt;(add_two(3))().result() &lt;&lt; std::endl; return 0; } // output is 11 (3+2+2+2+2) </code></pre> <p><strong>Using a closure instead of an explicit function object</strong></p> <pre><code>int main(int argc, char* argv[]) { int accumulator{3}; repeat&lt;4&gt;( [&amp;](std::size_t) { accumulator += 2; })(); std::cout &lt;&lt; accumulator &lt;&lt; std::endl; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload