Search code examples
c++streamiostreamfstreamostream

How to "parametrize" an output stream?


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.


Solution

  • 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.