Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Picking up a discussion with @v.oddou a couple of years later, C++17 has finally delivered a way to do the originally macro-based type-agnostic solution (preserved below) <em>without</em> going through macro uglyness.</p> <pre><code>template &lt; typename... Args &gt; std::string sstr( Args &amp;&amp;... args ) { std::ostringstream sstr; ( sstr &lt;&lt; std::dec &lt;&lt; ... &lt;&lt; args ); return sstr.str(); } </code></pre> <p>Usage:</p> <pre><code>int i = 42; std::string s = sstr( "i is: ", i ); puts( sstr( i ).c_str() ); Foo x( 42 ); throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) ); </code></pre> <hr> <p><strong>Original answer:</strong></p> <p>Since "converting ... to string" is a recurring problem, I always define the <a href="http://rootdirectory.ddns.net/dokuwiki/doku.php?id=software:sstr" rel="noreferrer">SSTR()</a> macro in a central header of my C++ sources:</p> <pre><code>#include &lt;sstream&gt; #define SSTR( x ) static_cast&lt; std::ostringstream &amp; &gt;( \ ( std::ostringstream() &lt;&lt; std::dec &lt;&lt; x ) ).str() </code></pre> <p>Usage is as easy as could be:</p> <pre><code>int i = 42; std::string s = SSTR( "i is: " &lt;&lt; i ); puts( SSTR( i ).c_str() ); Foo x( 42 ); throw std::runtime_error( SSTR( "Foo is '" &lt;&lt; x &lt;&lt; "', i is " &lt;&lt; i ) ); </code></pre> <p>The above is C++98 compatible (if you cannot use C++11 <code>std::to_string</code>), and does not need any third-party includes (if you cannot use Boost <code>lexical_cast&lt;&gt;</code>); both these other solutions have a better performance though.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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