lutherbaker@yahoo.com (Luther Baker) wrote in message
[color=blue]
> I'd like to include some very simple logging in my app - removable at
> compile time.
>
> Avoiding macros .. I want to make sure this nonsense would be
> optimized away by the compiler if I don't need it.
>
>
> template<bool b>
> void
> log(const char* msg)
> {
> if (b == true)
> {
> std::cout << msg << std::endl;
> }
> }
>
> ...
>
> const bool is_log_on = false;
>
> int
> main(int argc, char* argv)
> {
> ...
> log<is_log_on>("I am here.");
> ...
> }
>
>
>
> Since "is_log_on" evaluates to false at compile time, I'm hoping the
> compiler optimizes it away so there is absolutely no affect on
> performance. Is there a well-known problem with this approach or
> extending it into a full blown out logging template class?[/color]
The optimization may happen on your compiler -- check the assembly to
be sure. To improve the chances of optimization, make the function
inline. If this doesn't work, provide a specialization of log<false>
which does nothing and dispense with the if statement inside
log<true>. Let us know your findings, what compiler you used,
compiler flags, etc.
Note one normally says,
log << "hello" << x+1;
So even if logging is off, the compiler may still evaluate "hello" and
x+1. If it knows that evaluating x+1 has no side effects and
operator<< does nothing if bool is_log_on = false, then it need not
evaluate x+1. But I don't think most compilers do this level of
optimization.
As a design issue, I'd declare const bool _log_on = true or false at
the top, and so in code I just write log("I am here."); instead of
log<is_log_on>("I am here.");. But that's your call.