Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ format macro / inline ostringstream
    text
    copied!<p>I'm trying to write a macro that would allow me to do something like: <code>FORMAT(a &lt;&lt; "b" &lt;&lt; c &lt;&lt; d)</code>, and the result would be a string -- the same as creating an ostringstream, inserting <code>a...d</code>, and returning <code>.str()</code>. Something like:</p> <pre><code>string f(){ ostringstream o; o &lt;&lt; a &lt;&lt; "b" &lt;&lt; c &lt;&lt; d; return o.str() } </code></pre> <p>Essentially, <code>FORMAT(a &lt;&lt; "b" &lt;&lt; c &lt;&lt; d) == f()</code>.</p> <p>First, I tried:</p> <pre><code>1: #define FORMAT(items) \ ((std::ostringstream&amp;)(std::ostringstream() &lt;&lt; items)).str() </code></pre> <p>If the very first item is a C string (<code>const char *</code>), it will print the address of the string in hex, and the next items will print fine. If the very first item is an <code>std::string</code>, it will fail to compile (no matching operator <code>&lt;&lt;</code>).</p> <p>This:</p> <pre><code>2: #define FORMAT(items) \ ((std::ostringstream&amp;)(std::ostringstream() &lt;&lt; 0 &lt;&lt; '\b' &lt;&lt; items)).str() </code></pre> <p>gives what seems like the right output, but the <code>0</code> and <code>\b</code> are present in the string of course.</p> <p>The following seems to work, but compiles with warnings (taking address of temporary):</p> <pre><code>3: #define FORMAT(items) \ ((std::ostringstream&amp;)(*((std::ostream*)(&amp;std::ostringstream())) &lt;&lt; items)).str() </code></pre> <p>Does anyone know why 1 prints the address of the c-string and fails to compile with the <code>std::string</code>? Aren't 1 and 3 essentially the same?</p> <p>I suspect that C++0x variadic templates will make <code>format(a, "b", c, d)</code> possible. But is there a way to solve this now?</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