[英]can i pass std::ostream& to a function expecting std::ofstream
What i'm trying to do is: I want to redirect my error message erither to std::cerr or to a file depending upon the command-line
argument.我想要做的是:我想根据command-line
参数将我的错误消息重定向到 std::cerr 或文件。 If there is no log file provided then the program should output the error message on screen.如果没有提供日志文件,那么程序应该 output 屏幕上的错误消息。 Here is my approach:这是我的方法:
class A {
void SetLogFileStream(T& err_outstream);
};
//main.cpp //main.cpp
A a;
std::string filename;
T1* t1;
if(argc>2) {
filename = argv[1]; //if provided by command line
std::ofstream fp(filename);
t1 = &fp;
}
else {
std::ostream* err_outstream = &std::cerr;
t1 = err_outstream;
}
a.SetLogFileStream(t1);
what should be the argument type of the function SetLogFileStream
or the type T1
so that i can pass a pointer either to file or to std::cerr
function SetLogFileStream
的参数类型或T1
类型应该是什么,以便我可以将指针传递给文件或std::cerr
No. But the reverse is true.不,但反过来也是如此。 You can pass an std::ofstream
to a function expecting an std::ostream&
, or an std::ofstream*
to a function expecting an std::ostream*
.您可以将std::ofstream
传递给期望std::ostream&
的 function ,或将std::ofstream*
传递给期望std::ostream*
的 function 。 So your function should accept either an std::ostream
ref or pointer.因此,您的 function 应该接受std::ostream
引用或指针。
Declare the method as this:将方法声明为:
class A {
void SetLogStream(std::ostream& err_outstream);
};
There are several problems with your code.您的代码有几个问题。 The file stream opened gets out of scope and is destroyed.打开的文件 stream 脱离 scope 并被销毁。 You need to fix it like this:你需要像这样修复它:
std::ofstream f; // <-- this have to remain in scope while you use it for 'a'
A a;
if(args > 2) {
f.open(argv[1]);
a.SetLogStream(f);
} else {
a.SetLogStream(cerr);
}
The type should be std::ostream.类型应该是 std::ostream。 It woun't work exactly as you've coded it because your function parameter is a reference and your argument is a pointer.它不会完全按照您的编码工作,因为您的 function 参数是一个引用,而您的参数是一个指针。 But fix that (either way) and it will work.但是解决这个问题(无论哪种方式),它都会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.