my_macro << 1 << "hello world" << blah->getValue() << std::endl;
should expand into:
std::ostringstream oss;
oss << 1 << "hello world" << blah->getValue() << std::endl;
ThreadSafeLogging(oss.str());
my_macro << 1 << "hello world" << blah->getValue() << std::endl;
should expand into:
std::ostringstream oss;
oss << 1 << "hello world" << blah->getValue() << std::endl;
ThreadSafeLogging(oss.str());
Take a look at google-glog, they do this using a temporary object instanciated with a
and they also have other interesting macros such as LOG_IF et al.
Considering you have these lines included somewhere in your code, yes it is possible
__LINE__
macro is defined by all standart compilers. So we can use it to generate a variable name wich is different each time you use the macro :)Here is a new version that is seen as a one-statement instruction only: (EDITED)
Developper probably won't need to use this macro twice on same line becasue of simplicity of operator
<<
. But in case you need this, you can switch the use of__LINE__
by__COUNTER__
(which is non standard!). Thanks to Quuxplusone for this tipThe logging setup I have is quite similar:
If your logging is disabled, the ostream is never created and little overhead exists. You can configure logging on file name & line number(s) or priority levels. The ShouldLog function can change between invocations, so you could throttle or limit output. The log output uses two functions to modify itself, Prefix that adds a "file:line: (PRIO) " prefix to the line, and Flush() which both flushes it to the log output as a single command and adds a newline to it. In my implementation it always does, but you can make that conditional if one is not already there.
Couldn't you just derive from ostream and provide your own thread safe implementation? Then you could just do
And get the exact same functionality without macros and using C++ properly?
No. The problem is that without using function syntax, a macro is limited to only being replaced where it is.
But if you were willing to use function syntax, you can then replace stuff both before and after the args.
You could by defining MyMacro as:
Here's another nasty trick I saw somewhere else. It has a significant disadvantage compared to my other answer: you can't use it twice in the same scope because it declares a variable. However, it may still be interesting for other cases where you want to have
somemacro foo
run something afterfoo
.