简体   繁体   中英

C++ assign a logical operator function to a variable

I am trying to assign a logical operator function to a variable but am unable to get it to work. I am using:

function<bool(double,double)> opFunct = less<bool>();
double highorlow = pOut.high;
if(pCheck){
     opFunct = greater<bool>();
     highorlow = pOut.low;
}
if(opFunct(highorlow,pStay.middle){
     //never gets done
}

The problem with this code is no matter what the highorlow,pStay.middle doubles are, it returns false.

What am I missing?

Thanks

Short version :

less<bool> compares bool s. Use less<double> to compare double s (also in greater<> ).

Long version :

This is an interesting question. Specifically, how come the following line compiles?

function<bool(double, double)> opFunct = less<bool>();

After allstd::less<bool> :: operator() looks like bool(bool, bool) , why does it match bool(double, double) ?

Well that's because the check that std::function 's constructor performs is simply whether less<bool>() can be invoked as bool(double, double) , and yes it can! double is implicitly-convertible to bool , 0.0 becomes false and any other value true .

That obviously won't produce the expected result because eg opFunct(1.0, 2.0) will invoke less(true, true) which will return false .

The fix is to change bool to double

function<bool(double, double)> opFunct = less<double>();

And also here

    opFunct = greater<double>();

But wait, std::function overhead aside 1 , depending on how the rest of your code looks like, the fragment shown can potentially be simplified to just:

if (pCheck ? pStay.middle < pOut.low : pOut.high < pStay.middle) {
    // . . .
}

Or maybe even

if (pStay.middle < pOut.low || pOut.high < pStay.middle) {
    // both checks at once . . .
}

1 std::function comes at a cost of some 48-96 bytes of memory and an extra indirection or two. Compare the generated code for version with std::function vs. version without std::function .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM