Possible Duplicate:
Implementing a no-op std::ostream
Is there any stream equivalent of NULL in c++? I want to write a function that takes in a stream if the user wants to have the internal outputted to somewhere, but if not, the output goes into some fake place
void data(std::stream & stream = fake_stream){
stream << "DATA" ;
}
i want to be able to chose to do data() or data(std::cout)
Edit: Taken from @Johannes Schaub – litb’s mail here with slight modifications:
Use those:
Now, this looks cool and all, but the following is way shorter and works, because if a null pointer is provided to the constructor of
ostream, it automatically sets the badbit and silently ignores any writes:The standard guarantees this works, beginning from
27.6.2.2 [lib.ostream.cons] p1which describes the constructor ofostreamthat takes a pointer to astreambuf:The relevant function from
basic_ios,27.4.4.1 [lib.basic.ios.cons] p3:The important row from Table 89:
What happens if the
badbitis set is described under27.6.2.6 [lib.ostream.unformatted]:This implies that, in case the
sentryis false, it does not. Here is how thesentryconverts tobool, taken from27.6.2.3 [lib.ostream::sentry] p3 & p5:(
ok_is a member ofostream::sentryof typebool.)Note that these quotes are still present in C++11, just in different places. In order of appearance in this answer:
27.6.2.2 [lib.ostream.cons] p1=>27.7.3.2 [ostream.cons] p127.4.4.1 [lib.basic.ios.cons] p3=>27.5.5.2 [basic.ios.cons]27.6.2.6 [lib.ostream.unformatted]=>27.7.3.7 [ostream.unformatted] p127.6.2.3 [lib.ostream::sentry] p3 & p5=>27.7.3.4 [ostream::sentry] p4 & p5