A. K.
A. K.

Reputation: 38166

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

Upvotes: 2

Views: 1171

Answers (3)

Juraj Blaho
Juraj Blaho

Reputation: 13451

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);
}

Upvotes: 2

john
john

Reputation: 87957

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.

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

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.

Upvotes: 3

Related Questions