Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can C++ and C variadic arguments be used together?
    text
    copied!<p>Generally, using the C++11 variadic template feature with functions requires the variadic-based function arguments to be the last in the function argument list. There is one exception; they are the next-to-last arguments if there are C-level variadic arguments, which must be dead last.</p> <pre><code>template &lt; typename ...Args &gt; int super_printf( Something x, Args &amp;&amp;...a, ... ); </code></pre> <p>I sometimes randomly think about C++, and I wondered how such a function can be implemented. I first thought about the usual recursive peeling of arguments from <em>a</em>, then I remembered that the C-level varargs don't cascade. I have to turn them to a definitive va_list right away.</p> <pre><code>template &lt; typename ...Args &gt; int super_vaprintf( Something x, std::va_list &amp;aa, Args &amp;&amp;...a ); // Note that "aa" is passed by reference. template &lt; typename ...Args &gt; int super_printf( Something x, Args &amp;&amp;...a, ... ) { std::va_list args2; int result; va_start( args2, XXX ); // (A) try { result = super_vaprintf( x, args2, std::forward&lt;Args&gt;(a)... ); } catch ( ... ) { va_end( args2 ); // (1) throw; } va_end( args2 ); // (2) return result; // Can (1) and (2) be compacted with RAII using a custom deleter lambda // in std::unique_ptr or something? Remember that "va_end" is a macro! } </code></pre> <p>The usual C++ variadic recursive peeling happens in the <code>super_vaprintf</code> call. At line (A), what goes in the place of <code>XXX</code>, "a" or "a..."? What happens if <em>a</em> is empty, does <em>x</em> go there instead? If that last question's true, are we screwed if there's no <em>x</em>; that there's no arguments besides the variadic ones? (And if it's true, how do we conditionalize the code to use <em>x</em> when <em>a</em> is empty, and <em>a</em> otherwise?)</p> <p>...</p> <p>I just looked at my copy of the C++11 standard for any assistance here. There doesn't seem to be any. This would prompt a request for the C++ committee to come back to fix this, but I'm not sure that there's any way such a function could be called without the C++ varargs taking everything. Am I wrong; can a function call be made to use both C++ and C varargs? Or is mixing only useful for declarations, in terms of Stupid (Template) Instantiation Tricks?</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