I created my own std::cout
-like object that writes both to std::cout
and to a log file.
I'm currently defining it like this in a header file, but I'm getting unused variable warnings.
Header file <MyLib/Log.h>
static LOut { };
static LOut lo;
template<typename T> inline LOut& operator<<(LOut& mLOut, const T& mValue)
{
std::string str{toStr(mValue)};
std::cout << str;
getLogStream() << str;
return mLOut;
}
Usage:
#include <MyLib/Log.h>
...
lo << "hello!" << std::endl;
Should lo
be static
? Should lo
be extern
?
Kudos for explaining the correct way of declaring a cout
-like object and showing how the main standard library implementations do it.
Edit: by cout
-like object, I mean a global variable that is always available after including the corresponding header.
The cout object in C++ is an object of class ostream. It is defined in iostream header file. It is used to display the output to the standard output device i.e. monitor. It is associated with the standard C output stream stdout.
cout is an object of class ostream that represents the standard output stream. It can write characters either as formatted data using for example the insertion operator ostream::operator<< or as Unformatted data using the write member function. Save this answer.
std::cout is initialized using a pointer to an instance of some implementation-defined derived class of std::basic_streambuf . If you want more details, you need to specify what implementation you're asking about. It sounds like you won't be satisfied until you see the actual code for a standard library implementation.
std::cout
is simply declared as follows:
namespace std {
extern ostream cout;
}
It is a regular global variable; you can do the same thing yourself. Put an extern
declaration of your variable in a header; then define the same variable in a source file and link it to your application:
// mylog.h
extern MyLog mylog;
// mylog.cpp
MyLog mylog(someparams);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With