Note that there are some explanatory texts on larger screens.

plurals
  1. PODifference between code generated using a template function and a normal function
    text
    copied!<p>I have a vector containing large number of elements. Now I want to write a small function which counts the number of even or odd elements in the vector. Since performance is a major concern I don't want to put an if statement inside the loop. So I wrote two small functions like:</p> <pre><code>long long countOdd(const std::vector&lt;int&gt;&amp; v) { long long count = 0; const int size = v.size(); for(int i = 0; i &lt; size; ++i) { if(v[i] &amp; 1) { ++count; } } return count; } long long countEven(const std::vector&lt;int&gt;&amp; v) { long long count = 0; const int size = v.size(); for(int i = 0; i &lt; size; ++i) { if(0 == (v[i] &amp; 1)) { ++count; } } return count; } </code></pre> <p>My question is can I get the same result by writing a single template function like this:</p> <pre><code>template &lt;bool countEven&gt; long long countTemplate(const std::vector&lt;int&gt;&amp; v1) { long long count = 0; const int size = v1.size(); for(int i = 0; i &lt; size; ++i) { if(countEven) { if(v1[i] &amp; 1) { ++count; } } else if(0 == (v1[i] &amp; 1)) { ++count; } } return count; } </code></pre> <p>And using it like this:</p> <pre><code>int main() { if(somecondition) { countTemplate&lt;true&gt;(vec); //Count even } else { countTemplate&lt;false&gt;(vec); //Count odd } } </code></pre> <p>Will the code generated for the template and non-template version be the same ? or will there be some additional instructions emitted?</p> <p>Note that the counting of numbers is just for illustration hence please don't suggest other methods for counting.</p> <p><strong>EDIT</strong>: Ok. I agree that it may not make much sense from performance point of view. But atleast from maintainability point of view I would like to have only one function to maintain instead of two. </p>
 

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