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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With