如何“参数化”输出流?

时间:2017-01-26 18:17:23

标签: c++ stream iostream fstream ostream

如何使这个伪代码工作?

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

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

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

这不会编译,因为std::ostream没有公共默认构造函数。

2 个答案:

答案 0 :(得分:1)

在您的情况下,您可以使用三元运算符:

std::ostream& ostr = (condition ?
                      std::cout :
                      (ofstr.open("file.txt"), ofstr)); // Comma operator also used
                                                        // To allow fstream initialization.

答案 1 :(得分:0)

此实现可以切换到其他流:

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;