Hi,
how do I bind a std::ostream
to either std::cout
or to an std::ofstream
object, depending on a certain program condition? Although this invalid for many reasons, I would like to achieve something that is semantically equivalent to the following:
std::ostream out = condition ? &std::cout : std::ofstream(filename);
I've seen some examples that are not exception-safe, such as one from http://www2.roguewave.com/support/docs/sourcepro/edition9/html/stdlibug/34-2.html:
int main(int argc, char *argv[])
{
std::ostream* fp; //1
if (argc > 1)
fp = new std::ofstream(argv[1]); //2
else
fp = &std::cout //3
*fp << "Hello world!" << std::endl; //4
if (fp!=&std::cout)
delete fp;
}
Does anyone know a better, exception-safe solution?