When using variadic macros you need __VA_ARGS__
to expand all the arguments.
The problem however is that those arguments are comma-separated. Presumabely it just separates arguments to a function call, but since macros works with just text you can actually use __VA_ARGS__
in other contexts as well, where a comma-separated list makes sense.
The trick you can employ is to define your own comma operator for std::ostream
(the type of std::cout
). For example:
#include<iostream>
#define LOG(...) std::cout , __VA_ARGS__ , std::endl
template <typename T>
std::ostream& operator,(std::ostream& out, const T& t) {
out << t;
return out;
}
//overloaded version to handle all those special std::endl and others...
std::ostream& operator,(std::ostream& out, std::ostream&(*f)(std::ostream&)) {
out << f;
return out;
}
int main() {
LOG("example","output","filler","text");
return 0;
}
Now, the LOG invocation will expand to:
std::cout , "example" , "output" , "filler" , "text" , std::endl;
and the commas will invoke the overloaded comma operators.
If you don't like overloaded operator,
polluting all std::ostream
-s, you can encapsulate std::cout
with your own special logger class.