How to implement short circuit assessment in user functions?

Some operators, such as && and || perform a short circuit assessment. In addition, when a function is called with arguments, all arguments are constructed before the function is called.

For example, 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 is evaluated before calling f3 . But if I used the (regular) operator|| instead of f3 than the previous code would be equivalent

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

and f1 will not be evaluated if f2 is true.

My question is: is it possible that f3 (a user-defined function with two Boolean) behaves the same? If not, what does operator|| so special?

+4
source share
3 answers

No, if f3 () takes the values โ€‹โ€‹of the result of the functions.

But if it accepts the address of functions (or a more general one treats its input as functors) and not the results, then f3 () can decide whether 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); } 
+2
source

Your premise is incorrect. Overloaded operator|| and operator&& always evaluate both arguments; no short circuit.

See clause 7 More Effective C ++ for a discussion of this.

0
source

You can not compare || operator and similar functions. || is a logical operator and checks the given values, if the left operand is evaluated as false, then there is no need to check the correctness.

In the case of functions, any value returned by f1 () or f2 () is valid for f3 (). It is not possible to enable the logical operand function for function parameters, even if they accept bool parameters.

0
source

Source: https://habr.com/ru/post/1398153/


All Articles