title: Compile time sizeof_array without using a macro
body: <p>This is just something that has bothered me for the last couple of days, I don't think it's possible to solve but I've seen template magic before.</p>
  
  <p>Here goes:</p>
  
  <p>To get the number of elements in a standard C++ array I could use either a macro (1), or a typesafe inline function (2):</p>
  
  <p><strong>(1)</strong></p>
  
  <pre><code>#define sizeof_array(ARRAY) (sizeof(ARRAY)/sizeof(ARRAY[0]))
  </code></pre>
  
  <p><strong>(2)</strong></p>
  
  <pre><code>template &lt;typename T&gt;
  size_t sizeof_array(const T&amp; ARRAY){
      return (sizeof(ARRAY)/sizeof(ARRAY[0]));
  }
  </code></pre>
  
  <p>As you can see, the first one has the problem of being a macro (for the moment I consider that a problem) and the other one has the problem of not being able to get the size of an array at compile time; ie I can't write:</p>
  
  <pre><code>enum ENUM{N=sizeof_array(ARRAY)};
  </code></pre>
  
  <p>or</p>
  
  <pre><code>BOOST_STATIC_ASSERT(sizeof_array(ARRAY)==10);// Assuming the size 10..
  </code></pre>
  
  <p>Does anyone know if this can be solved?</p>
  
  <p><strong><em>Update</strong>:</em></p>
  
  <p>This question was created before constexpr was introduced. Nowadays you can simply use:</p>
  
  <pre><code>template &lt;typename T&gt;
  constexpr auto sizeof_array(const T&amp; iarray) {
      return (sizeof(iarray) / sizeof(iarray[0]));
  }
  </code></pre>