Question

Say I have the following code:

int ignored = 0;
StreamIgnore si;

si << "This part" << " should be" << ignored << std::endl;

I want that when this code runs si will simply ignore the rest of the stream. The thing is I want this to be as efficient as possible. One obvious solution would be to have:

template <typename T>
StreamIgnore& opertaor<<(const T& val) {
    //Do nothing
    return *this;
}

BUT, if the code was something like:

StreamIgnore si;

si << "Fibonacci(100) = " << fib(100) << std::endl;

Then I'll have to calculate fib(100) before the //Do Nothing part. So, I want to be able to ignore the rest completely without any unnecessary computations.

To make this request make sense, think that StreamIgnore could be a StreamIgnoreOrNot class, and the c'tor decides whether to ignore the stream or not by either returning *this and use the stream, or a new StreamIgnore() instance and ignoring the rest.

I thought about using Macros some how but could't come up with something that enables me to use this syntax (i.e "si << X << Y...").

I would appreciate it if someone could suggest a way to do that.

Thanks

Was it helpful?

Solution

I 'd obviously use IOstreams with disabling/enabling the output amounting to setting/clearing std::ios_base::failbit. Doing this will readily prevent formatting and writing the data. It won't prevent evaluation of arguments, though. For that purpose I'd use the logical and operator:

si && si << not_evaluated() << when_not_used();

OTHER TIPS

There is no way to do this (without cheating, as you will see below). Your code is only passed the result of fib(100) and as such cannot short-circuit execution here at all.

However, there is a simple hack you can use:

template<typename T> struct is_ignored { static const bool yes = false; };
template<> struct is_ignored<StreamIgnore> { static const bool yes = true; };

#define S(x) if(!is_ignored<remove_reference<decltype(x)>::type>::yes) x
S(x) << "meep\n";

You may have to add some _Pragmas to disable compiler warnings about the fact that this leads to dead code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top