开发者

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. If there is no log file provided then the program should output the error message on screen. Here is my approach:

class A {

    void SetLogFileStream开发者_JS百科(T& err_outstream);
};

//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


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*. So your function should accept either an std::ostream ref or pointer.


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. 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. It woun't work exactly as you've coded it because your function parameter is a reference and your argument is a pointer. But fix that (either way) and it will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜