Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>N</code> does not get "initialized" to anything. It is not a variable. It is not an object. <code>N</code> is a compile-time constant. <code>N</code> only exists during compilation. The value of <code>N</code> as well as the actual <code>T</code> is determined by the process called <em>template argument deduction</em>. Both <code>T</code> and <code>N</code> are deduced from the actual type of the argument you pass to your template function. </p> <p>In the first call the argument type is <code>int[6]</code>, so the compiler deduces that <code>T == int</code> and <code>N == 6</code>, generates a separate function for that and calls it. Let's name it <code>cal_size_int_6</code></p> <pre><code>void cal_size_int_6(int (&amp;a)[6]) { std::cout &lt;&lt; "size of array is: " &lt;&lt; 6 &lt;&lt; std::endl; } </code></pre> <p>Note that there's no <code>T</code> and no <code>N</code> in this function anymore. Both were replaced by their actual deduced values at compile time.</p> <p>In the first call the argument type is <code>int[1]</code>, so the compiler deduces that <code>T == int</code> and <code>N == 1</code>, generates a separate function for that as well and calls it. Let's name it <code>cal_size_int_1</code></p> <pre><code>void cal_size_int_1(int (&amp;a)[1]) { std::cout &lt;&lt; "size of array is: " &lt;&lt; 1 &lt;&lt; std::endl; } </code></pre> <p>Same thing here. </p> <p>Your <code>main</code> essentially translates into</p> <pre><code>int main() { int a[]={1,2,3,4,5,6}; int b[]={1}; cal_size_int_6(a); cal_size_int_1(b); } </code></pre> <p>In other words, your <code>cal_size</code> template gives birth to <em>two different functions</em> (so called <em>specializations</em> of the original template), each with different values of <code>N</code> (and <code>T</code>) hardcoded into the body. That's how templates work in C++.</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