Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As Matthew Wilson discusses in <a href="http://www.imperfectcplusplus.com/" rel="nofollow noreferrer"><em>Imperfect C++</em></a>, this can be used to enforce type safety in C++, by preventing use of <code>DIMENSION_OF()</code>-like macros with instances of types that define the subscript operator, as in:</p> <pre><code>#define DIMENSION_OF_UNSAFE(x) (sizeof(x) / sizeof((x)[0])) #define DIMENSION_OF_SAFER(x) (sizeof(x) / sizeof(0[(x)])) int ints[4]; DIMENSION_OF_UNSAFE(ints); // 4 DIMENSION_OF_SAFER(ints); // 4 std::vector v(4); DIMENSION_OF_UNSAFE(v); // gives impl-defined value; v likely wrong DIMENSION_OF_SAFER(v); // does not compile </code></pre> <p>There's more to this, for dealing with pointers, but that requires some additional template smarts. Check out the implementation of <code>STLSOFT_NUM_ELEMENTS()</code> in the <a href="http://www.stlsoft.org/" rel="nofollow noreferrer">STLSoft</a> libraries, and read about it all in chapter 14 of <a href="http://www.imperfectcplusplus.com/" rel="nofollow noreferrer"><em>Imperfect C++</em></a>.</p> <p>edit: some of the commenters suggest that the implementation does not reject pointers. It does (as well as user-defined types), as illustrated by the following program. You can verify this by uncommented lines 16 and 18. (I just did this on Mac/GCC4, and it rejects both forms).</p> <pre><code>1 2 #include &lt;stlsoft/stlsoft.h&gt; 3 4 #include &lt;vector&gt; 5 6 #include &lt;stdio.h&gt; 7 8 int main() 9 { 10 int ar[1]; 11 int* p = ar; 12 std::vector&lt;int&gt; v(1); 13 14 printf("ar: %lu\n", STLSOFT_NUM_ELEMENTS(ar)); 15 16 // printf("p: %lu\n", STLSOFT_NUM_ELEMENTS(p)); 17 18 // printf("v: %lu\n", STLSOFT_NUM_ELEMENTS(v)); 19 20 return 0; 21 } 22 </code></pre>
 

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