C++ stream library has pretty ancient design.
Nevertheless - its basic idea is that ostream or istream are just wrapper objects over stream-buffers.
So you might try something like in this code:
std::ostream get_log(bool str) {
if (str) return std::ostream(new std::stringbuf());
// else
std::filebuf* f = new std::filebuf();
f->open("log", std::ios_base::out);
return std::ostream(f);
}
But, as I mentioned, this is very ancient design - so no RAII - this buffer is not owned by stream - you would need to delete it by yourself:
int main() {
std::ostream log = get_log(true);
log << "aaa";
std::cout << static_cast<std::stringbuf&>(*log.rdbuf()).str();
delete log.rdbuf(); // (!)
}
So this is not very usable.
So my final advice - use smart pointer over ostream - like this:
std::unique_ptr<std::ostream> get_log(bool str) {
if (str) return new std::ostringstream();
std::ofstream* f = new std::ofstream();
f->open("log", std::ios_base::out);
return f;
}
int main() {
auto log = get_log(true);
*log << "aaa";
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…