Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Think of it this way, suppose you had a bunch of functions:</p> <pre><code>// Note that you don't need to name the array, since you don't // actually reference the parameter at all. size_t array_size(const int (&amp;)[1]) { return 1; } size_t array_size(const int (&amp;)[2]) { return 2; } size_t array_size(const int (&amp;)[3]) { return 3; } // etc... </code></pre> <p>Now when you call this, which function gets called?</p> <pre><code>int a[2]; array_size(a); </code></pre> <p>Now if you templatize the arraysize, you get:</p> <pre><code>template &lt;int n&gt; size_t array_size(const int (&amp;)[n]) { return n; } </code></pre> <p>The compiler will attempt to instantiate a version of array_size that matches whatever parameter you call it with. So if you call it with an array of 10 ints, it will instantiate array_size with n=10. </p> <p>Next, just templatize the type, so you can call it with more than just int arrays:</p> <pre><code>template &lt;typename T, int n&gt; size_t array_size(const T (&amp;)[n]) { return n; } </code></pre> <p>And you're done.</p> <p><strong>Edit</strong>: A note about the <code>(&amp;)</code></p> <p>The parentheses are needed around the <code>&amp;</code> to differentiate between array of int references (illegal) and reference to array of ints (what you want). Since the precedence of <code>[]</code> is higher than <code>&amp;</code>, if you have the declaration:</p> <pre><code>const int &amp;a[1]; </code></pre> <p>because of operator precedence, you end up with a one-element array of const references to int. If you want the <code>&amp;</code> applied first, you need to force that with parentheses:</p> <pre><code>const int (&amp;a)[1]; </code></pre> <p>Now the you have a const reference to a one element array of ints. In the function parameter list, you don't need to specify the name of a parameter if you don't use it, so you can drop the name, but keep the parentheses:</p> <pre><code>size_t array_size(const int (&amp;)[1]) </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. 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