Can i design my logging-function in a way, that it accepts concatenated strings of the following form using C++?
int i = 1;
customLoggFunction("My Integer i = " << i << ".");
.
customLoggFunction( [...] ){
[...]
std::cout << "Debug Message: " << myLoggMessage << std::endl << std::endl
}
Edit:
Using std::string as the attribute to the function works for the concatenated string, but then a passed non-concatenated string like customLoggFunction("example string") produces a compile-time error saying the function is not applicable for char[]. When i overload the function in the following way...
customLoggFunction(std::string message){...}
customLoggFunction(char message[]){...}
... the concatenated strings seize to work.
I uploaded the code: http://coliru.stacked-crooked.com/a/d64dc90add3e59ed
You could do it by defining a new operator<<. From vague memory, implementing functions with these three signatures will do the trick:
Each of them has to concatenate its arguments and return a std::string.
Howeever, it feels wrong. Goes against the grain of C++. I suggest a more C++-ish solution, namely to make your logger into a class, and write operator<<() members for that class, so you can run
One approach is a simple utility class that uses a standard stream in a templated member function:
The stream member doing all the work is then used in the destructor,
and you can create temporary objects for passing your arguments to be concatenated:
Additional state (e.g. a log level) can be passed to the constructor, often accompagnied by convenience functions like
LogStream debug() { return LogStream(...); }
. When you reach a certain point of sophistication though, you might want to switch to a logging library of course.It's impossible to do with the exact syntax you asked for unless you resort to macros.
But if you don't mind replacing
<<
with,
, then you can do following:For trivial projects this is one of the few things I use a
MACRO
for. You can do something like this:Generally
MACROS
should be avoided but there is no other way to get precisely this with a standard function. So...Note: The empty condition
do{...}while(0)
enables you to place theMACRO
in places that aMACRO
usually can't go if it contains multiple statements.