Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to "compile out" stream expressions in C++?

It is well established that you can use macros to make a version of printf that can be stripped from the code during compilation (say, if you want to only print on debug builds). The resulting code can be used exactly like one would use printf.

Is it possible to produce a similar scenario with respect to stream output?

For example, suppose I have the following code:

#include <iostream>

class Foo
{
public:
    template <typename T>
    Foo& operator <<(const T& input)
    {
        std::cout << input;
    }
};

int ComputeExpensiveThing(); // this function is expensive

void doSomething()
{
    Foo() << "Expensive thing:  " << ComputeExpensiveThing() << std::endl;
    // do other things
}

Is there a way to conditionally strip the first line of doSomething() at compile-time?

I can use a macro to get a similar effect by checking a global condition at runtime:

#define FOO if(!someGlobalCondition); else Foo()

void doSomething()
{
    FOO << "Expensive thing:  " << ComputeExpensiveThing() << std::endl;
}

However, this requires a conditional branch instruction each time we use FOO. It's a significant improvement over calling ComputeExpensiveThing, but I'd still prefer to remove the excess branches.

I've also seen an alternative that changes the target syntax to something like

void doSomething()
{
    Foo("Expensive thing:  " << ComputeExpensiveThing() << std::endl);
}

but the resulting syntax is a bit odd and unintuitive to some users.

like image 402
bobobo Avatar asked Feb 18 '15 23:02

bobobo


1 Answers

Why don't you just make the conditional something like this?

#ifdef DEBUG
#define dbglog std::cout
#else
#define dbglog if(0) std::cout
#endif

Then you can use it like so:

dbglog << "Hello, World!" << std::endl;

if(0) and the subsequent statement will be completely deleted by the compiler (clang even does this optimization with no -O flag specified!).

like image 87
nneonneo Avatar answered Nov 15 '22 01:11

nneonneo