I'd like to add a timestamp to certain outputs to the std::cout / std::cerr ostreams, without using modified standard streams, like so:
std::cerr << timestamp << "Warning!\n";
or so:
std::cerr << timestamp() << "Warning!\n";
The output should look like this:
[2020-01-23 17:40:15 CET] Warning!
But I'm really not happy with what I've come up with:
class TimeStamp {};
std::ostream &operator<<(std::ostream &stream, const TimeStamp &ts)
{
std::time_t t = std::time(nullptr);
stream << "[" << std::put_time(std::localtime(&t), "%F %T %Z") << "] ";
return stream;
}
TimeStamp ts;
int main()
{
std::cerr << ts << "Warning!\n";
std::cerr << ts << "Another warning!\n";
}
So I'm basically defining an empty class, using a global declaration and overloading the '<<' operator. This feels wrong. A static function like timestamp() is probably better suited, but I'm not quite sure how to go on about this. All the examples I've found online used the overloaded '<<' operator, but it usually made more sense to do so, because some class state was output. Can I locally create an ostream and return that in the function?
operator<<
do something special is not wrong at all. Do you see any disadvantages? Why do you think it is wrong? – Sorediumts
constexpr – Transportation