title: Counting function arguments at compile time
body: <p>I'm trying to count the number of arguments to a function at compile time (I'm wrapping sprintf up in some templates for compile time checks and type safety). I need to check that the number of arguments matches the number of formatting placeholders at compile time. A first pass at this is pretty simple:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>template &lt;typename... Args&gt;
  constexpr u32
  CountArgs(Args&amp;&amp;... args)
  {
      return sizeof...(args);
  }
  
  constexpr u32
  CountFormatSpecifiers(c8* format);
  
  template &lt;typename... Args&gt;
  c8*
  String_FormatImpl(c8* format, Args&amp;&amp;... args);
  
  #define String_Format(format, ...) \
      String_FormatImpl(format, __VA_ARGS__); \
      static_assert(CountFormatSpecifiers(format) == CountArgs(__VA_ARGS__));
  </code></pre>
  
  <p>But this breaks down for certain types of arguments. Namely, when passing a reference.</p>
  
  <pre class="lang-cpp prettyprint-override"><code>int x = 0;
  int&amp; xRef = x;
  String_Format("%", xRef);
  </code></pre>
  
  <p>The compiler complains about <code>CountArgs(__VA_ARGS__)</code> because <code>xRef</code> is not a constant expression. I don't need the value, just the ability to count it. I could wrap it in <code>sizeof</code> or something similar, but that's tough when all I have is <code>__VA_ARGS__</code> to work with.</p>
  
  <p>Example: <a href="https://godbolt.org/z/Diwffy" rel="nofollow noreferrer">https://godbolt.org/z/Diwffy</a></p>