title: Operator Overloading to Construct Exception Message
body: <p>I am changing some code in a legacy code base. Inside this code there is an often repeated pattern that looks like the following:</p>
  
  <pre><code>std::stringstream ss;
  ss &lt;&lt; ...;
  throw MyCustomException(ss.str());
  </code></pre>
  
  <p>Since I am modifying the code anyways I wanted to make something like the following:</p>
  
  <pre><code>throw MyCustomException() &lt;&lt; ...;
  </code></pre>
  
  <p>effectively removing the need for the <code>std::stringstream</code>.</p>
  
  <p>I found a solution:</p>
  
  <pre><code>struct MyCustomException: public std::runtime_error
  {
      MyCustomException(const std::string&amp; what_arg="")
      : std::runtime_error(what_arg)
      {
      }
  
  #if 0
      template&lt;typename T&gt;
      friend
      MyCustomException operator&lt;&lt;(MyCustomException e, const T&amp; obj)
      {
          std::stringstream ss;
          ss &lt;&lt; e.what();
          ss &lt;&lt; obj;
          return MyCustomException(ss.str());
      }
  #else
      template&lt;typename T&gt;
      MyCustomException operator&lt;&lt;(const T&amp; obj)
      {
          std::stringstream ss;
          ss &lt;&lt; what();
          ss &lt;&lt; obj;
          return MyCustomException(ss.str());
      }
  #endif
  };
  </code></pre>
  
  <p>Both solutions (<code>#if ... #endif</code>) work, but since everything is by value, a lot of copies of the exception object are created before it is thrown. Changing the signature to <code>MyCustomException&amp; e</code> produces a ton of compile time errors (why?).</p>
  
  <p>The whole problem is further complicated by the fact that I am bound to an old GCC revision that only supports C++03. So no fancy C++1[147] stuff here!</p>
  
  <p>Is there a better way to make my desired functionality (<code>throw MyCustomException() &lt;&lt; ...;</code>) work without the creation of the many temporary copies when throwing an exception?</p>