如何 "parametrize" 一个输出流?
How to "parametrize" an output stream?
我怎样才能使这个伪代码起作用?
std::ostream ostr;
std::ofstream ofstr;
if(condition) {
ostr = std::cout;
}
else {
ofstr.open("file.txt");
ostr = ofstr;
}
ostr << "Hello" << std::endl;
这不会编译,因为 std::ostream
没有 public 默认构造函数。
在您的情况下,您可以使用三元运算符:
std::ostream& ostr = (condition ?
std::cout :
(ofstr.open("file.txt"), ofstr)); // Comma operator also used
// To allow fstream initialization.
此实现可以切换到其他流:
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;
我怎样才能使这个伪代码起作用?
std::ostream ostr;
std::ofstream ofstr;
if(condition) {
ostr = std::cout;
}
else {
ofstr.open("file.txt");
ostr = ofstr;
}
ostr << "Hello" << std::endl;
这不会编译,因为 std::ostream
没有 public 默认构造函数。
在您的情况下,您可以使用三元运算符:
std::ostream& ostr = (condition ?
std::cout :
(ofstr.open("file.txt"), ofstr)); // Comma operator also used
// To allow fstream initialization.
此实现可以切换到其他流:
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;