I have heard several times, that one should avoid plain writes to std::cout
. (Is this correct?) However, I did not find good examples of how to achieve this. What I came up with so far is this:
#include <iostream>
class Logger {
std::ostream os;
auto RdBuffer( bool const decision ) { return decision ? std::cout.rdbuf() : nullptr; }
public:
explicit Logger( bool const use_cout = true ) : os( Buffer( use_cout ) ) {}
void Print() {
os << "Ptinting" << std::endl;
}
};
It allows me to write to std::cout
if wanted, or stays silent otherwise. It seems to work, but I'm not sure this is the correct approach. What worries me in particular is the initialization with the nullptr
and the consecutive writing to it in case the bool is set to false.
Is this going in the right direction? I'm particular interested in modern C++ ways of achieving this. So C++11 or newer answers are greatly appreciated.
Aucun commentaire:
Enregistrer un commentaire