-2

How can I make this pseudo-code work?

std::ostream  ostr;
std::ofstream ofstr;

if(condition) {
    ostr = std::cout;
}
else {
    ofstr.open("file.txt");
    ostr = ofstr;
}

ostr << "Hello" << std::endl;

This does not compile, since std::ostream does not have a public default constructor.

Pietro
  • 12,086
  • 26
  • 100
  • 193
  • The linked question isn't an _exact_ duplicate, but it's close enough, and the accepted answer shows a solution for your problem. – Useless Jan 26 '17 at 18:25
  • 1
    In your case you may use ternary operator: `std::ostream& ostr = (condition ? std::cout : (ofstr.open("file.txt"), ofstr));` – Jarod42 Jan 26 '17 at 18:34
  • @Jarod42: just tried; it works when `condition` is true, and I get the output on cout, but I get no file written when `condition` is false. – Pietro Jan 26 '17 at 18:55
  • [Demo](http://coliru.stacked-crooked.com/a/988e1cce31480232). – Jarod42 Jan 26 '17 at 19:21
  • To send data to multiple streams simultaneously: [http://stackoverflow.com/questions/1760726/how-can-i-compose-output-streams-so-output-goes-multiple-places-at-once](http://stackoverflow.com/questions/1760726/how-can-i-compose-output-streams-so-output-goes-multiple-places-at-once) – Pietro Jan 27 '17 at 11:22

2 Answers2

1

In your case you may use ternary operator:

std::ostream& ostr = (condition ?
                      std::cout :
                      (ofstr.open("file.txt"), ofstr)); // Comma operator also used
                                                        // To allow fstream initialization.
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

This implementation can switch to other streams:

std::ofstream ofstr;
std::ostream *ostr;

ofstr.open("file.txt");

ostr = &ofstr;
*ostr << "test --> file\n" << std::endl;

ostr = &std::cout;
*ostr << "test --> stdout\n" << std::endl;
Pietro
  • 12,086
  • 26
  • 100
  • 193