Note that there are some explanatory texts on larger screens.

plurals
  1. POAuto newlining ostream
    text
    copied!<p>Sorry in advance for the bad title, not sure what to call what I'm trying to do.</p> <p>Some background, if you don't care to read, skip to the next paragraph. I have a unit test class where I call assert with some condition and if it fails I output some string that was passed in. I have found that it is quite annoying to build a string to send to this if for instance I want to say <code>"Failed on index: " + i</code>. My idea is to return a <code>std::ostream</code> instead of taking a <code>std::string</code>. If the assert fails I return <code>std::cerr</code>, if the assert passes then I return a <code>std::stringstream</code>. I imagine I could do all of this just fine. I'd have to store a <code>std::stringstream</code> in my unit test class so I can return a reference.</p> <p>What I would like to do is instead of returning a standard <code>std::ostream</code> return an extended <code>std::ostream</code> that outputs <code>std::endl</code> when it's done so I don't have to remember it for each assert. In particular the idea is the following:</p> <pre><code>UnitTest("My test"); ut.assert(false) &lt;&lt; "Hello world"; ut.assert(1 == 0) &lt;&lt; "On the next line"; </code></pre> <p>The idea being that on destruction this new class would output the endline and that it would be destructed as soon as it was no longer used (i.e. no more &lt;&lt; operators). So far this is what I have (I've removed some of the code in assert, and it's actually inside a class, but this is sufficient to show what's going on):</p> <pre><code>class newline_ostream : public std::ostream { public: newline_ostream(std::ostream&amp; other) : std::ostream(other.rdbuf()){} ~newline_ostream() { (*this) &lt;&lt; std::endl; } }; newline_ostream&amp; assert(bool condition, std::string error) { if(!condition) { return newline_ostream(std::cerr); } return newline_ostream(std::stringstream()); } </code></pre> <p>When I try this method I get some stuff basically telling me that returning an object I just created is wrong because it's not an lvalue. When I try changing it to not return a reference it complains that there's no copy constructor (presumably this is because I'm extending <code>std::ostream</code> and it doesn't have a copy constructor).</p> <p>What I'm looking for is some method that causes the compiler to create a temporary newline_ostream that <code>assert()</code> will write it's result into that will die as soon as it's no longer used (i.e. no more &lt;&lt; operators). Is this possible and if so how?</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