I'm writing a simple debug utility class:
class MyDbg {
protected:
std::string filename;
std::ostream* fp;
std::ofstream fout;
public:
void setOutFile(std::string filename) {
if(filename == "terminal") {
fp = &std::cout;
} else {
fout.open(filename);
fp = &fout;
}
}
What I want to do is be able to set an instance of this to either std::cout
or to output to a file. And then be able to stream to an instance of this object as if I were streaming to std::cout (or an ofstream):
So the object should be able to take the <<() operator and support an input stream (like an stringstream) or basic types (like integer, char, etc.).
int main() {
MyDbg dbg;
dbg.setOutFile("terminal");
dbg << "foo" << std::endl;
dbg.setOutFile("dbg.log");
dbg << "bar" << std::endl;
}
I'm thinking this would require me to write my own stream child class? Does that sound about right? Or is there a way to overload an operator to do this?