Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Short-Circuit evaluation in user-defined functions?

Some operators such as && and || perform short-circuit evaluation. Also, when a function is called with arguments, all arguments are constructed before calling the function.

For instance, take the following three functions

bool f1();
bool f2();
bool f3(bool, bool);

if I call

if( f3(f2(),f1()) )//Do something

Then the return value of both f2 and f1 are evaluated before f3 is called. But, if I had used (the regular) operator|| instead of f3, than the code above would be equivalent to

if( f2()||f1() )//Do something

and f1 won't be evaluated if f2 evaluates to true.

My question is: is it possible to have f3 (a user defined function taking two booleans) behave the same way? If not, what makes the operator|| so special?

like image 893
Malabarba Avatar asked Feb 24 '12 00:02

Malabarba


1 Answers

Not if f3() takes the values of the result of the functions.

But if it takes the address of the functions (or more generically treats its input as functors) rather than the results then f3() can decide if it needs to call the function.

template<typename F1, typename F2>
bool f3(F1 const& f1, F2 const& f2)
{
    return f1() || f2();
}

bool f1();
bool f2();

int main()
{
    f3(&f1, &f2);
}
like image 73
Martin York Avatar answered Sep 28 '22 07:09

Martin York