【问题标题】:How to "parametrize" an output stream?如何“参数化”输出流?
【发布时间】:2017-01-26 18:17:23
【问题描述】:

我怎样才能使这个伪代码工作?

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

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

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

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

【问题讨论】:

标签: c++ stream iostream fstream ostream


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这个实现可以切换到其他流:

    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;
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2016-05-20
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多