I would like to log the return value of a function. The problem is that the function might have many exit points and I don't want to add a log call before every one of them.
I thought about having an inner object that's responsible on making the Log
call. But still, I would have to notify it about the return value before each return
statement.
I also thought about creating a macro that calls the logger before returning from the function. Something like:
#define RETURN(ret) Logger.log(__FUNCTION__, ret); return ret;
But I want to avoid doing that.
Any other thoughts on how I can achieve that nicely and easily?
Thanks
I don't think you can do that more nicely and easily. In this case I think the solution with least impact on the source is to use the preprocessor, but you shouldn't do it the way you do because it has surprices built in. Fx:
expands to:
which means that
something
is sent to the log ifdone
is true, thensomething
is returned anyway.To make the expansion fit into a single statement it's normally wrapped in a
do { ... } while(0)
which would make that example log and return only ifdone
is true.But there's still a surprise since the macro argument is expanded twice, consider the case where you write
RETURN(something++);
then it will expand toLogger.log(__FUNCTION__, something++); return something++;
which means unfortunate side effects. This was a real problem in C, but not in C++. Here templates are handy:Note that it is called
__func__
in the standard (an not__FUNCTION__
).