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

It is well known that you can use macros to create a version printfthat can be removed from code at compile time (say, if you want to print only on debug builds). The resulting code can be used in the same way as used printf.

Is it possible to create a similar scenario with respect to a stream?

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 delete the first line of doSomething () at compile time?

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

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

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

, FOO. ComputeExpensiveThing, .

, -

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

.

+4
2

- ?

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

:

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

if(0), (clang -O!).

+3

++, .

, const debug if (debug) do_something;. , , if , .

, , , ( ?).

- , .

+1

All Articles