简体   繁体   English

C++ 将逻辑运算符 function 分配给变量

[英]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.我正在尝试将逻辑运算符 function 分配给变量,但无法使其正常工作。 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.这段代码的问题是无论 highorlow,pStay.middle 双打是什么,它都会返回 false。

What am I missing?我错过了什么?

Thanks谢谢

Short version :短版

less<bool> compares bool s. less<bool>比较bool Use less<double> to compare double s (also in greater<> ).使用less<double>比较double s(也在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) ?毕竟std::less<bool> :: operator()看起来像bool(bool, bool) ,为什么它匹配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!那是因为std::function的构造函数执行的检查仅仅是less<bool>()是否可以作为bool(double, double)调用,是的,它可以! double is implicitly-convertible to bool , 0.0 becomes false and any other value true . double可隐式转换为bool0.0变为false ,任何其他值变为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 .这显然不会产生预期的结果,因为例如opFunct(1.0, 2.0)将调用less(true, true) ,这将返回false

The fix is to change bool to double解决方法是将bool更改为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:但是等等,除了1之外的std::function开销,具体取决于代码的 rest 的样子,显示的片段可能会简化为:

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. 1 std::function的代价是大约 48-96 字节的 memory 和一两个额外的间接。 Compare the generated code for version with std::function vs. version without std::function .将生成的版本代码与 std::function没有 std::function 的版本进行比较

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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