是否可以定义可以在以后评估的布尔表达式?

时间:2017-06-21 10:16:07

标签: c++ conditional-statements lazy-evaluation

希望获得一种动态表达式,我可以在以后评估布尔值。

condition &&= condition2; //not evaluated just yet
condition ||= condition3;    

if (condition)    //evaluated now
   do this;
else
   do this;

例如我在整个代码中使用相同的条件,如果我可以调整一个语句或者即使在程序运行时添加更多语句也会更容易。

conditions = (x>50 && y>200) && (type == MONKEY);
conditions &&= (x<75 && y<250);

以及稍后的代码

if (conditions)
    cout<<"Hello!";

编辑:应在if语句中评估条件。

5 个答案:

答案 0 :(得分:2)

使用&amp;&amp ;;时要非常小心和&amp;

<小时/> 原因1

扩展假定(和语法无效)

condition &&= condition2;

condition = condition && condition2;

揭示了一个微妙之处:如果condition2condition,则false 进行评估。

<小时/> 原因2

&&&对整数类型也有不同的行为,例如0b01 & 0b1000b01 && 0b10true(此处我使用的是C ++ 14二进制文字)。

<小时/> 结论

所以我赞成压缩

if (condition = condition && condition2){
    // do this
} else {
    // do this
}

仅在condition2condition

的情况下评估true

答案 1 :(得分:2)

这里明智的解决方案是为这些条件创建命名函数,并在必要时调用它们。

那说......

  

有可能[..]

当然。要推迟评估,只需将条件包装在(lambda)函数中即可。概念证明:

#include <functional>
#include <iostream>

template<typename F, typename G>
auto and_also (F f, G g) {
  return [=]() {
    bool first = f();
    if (! first) return false;
    return static_cast<bool>(g());
  };
}

int main () {
  int dummy = -1;
  std::function<bool()> condition = [&](){return dummy > 0;};
  condition = and_also(condition, [&](){return dummy < 42;});
  dummy = 21;
  if (condition()) std::cout << "in range" << std::endl;
}

答案 2 :(得分:1)

为了解决用例问题,您在评论中提到过:

  

示例:移动窗口中的像素并避开窗口的某些区域。

出于可读性的原因,我建议您定义一个函数,例如,像这样(伪代码)示例:

bool is_in_rect(point2i p, rect2i rect) {
    // check x range
    if (p.x >= rect.x1 && p.x < rect.x2)
        return true;
    // check y range
    if (p.y >= rect.y1 && p.y < rect.y2)
        return true;
    return false;
}

您可以根据需要为特殊情况添加功能:

bool is_in_monkey_rect(point2i p, rect2i rect) {
    return rect.type == MONKEY && is_in_rect(p, rect);
}
  

但总的来说,我只是想知道这是否可能。

除了委托给一个函数,你可能会使用宏来模拟这种懒惰的评估。但我不建议这样做。

请注意,根据问题的实际性质,调整迭代模式可能更有意义,而不是迭代所有数据并检查每个像素的相关性。

答案 3 :(得分:0)

在一个地方做某事的一种常见方式,所以你不要在任何地方重复自己,就是要发挥作用。

例如,

bool special_condition(bool current_condition, int x)
{
    return current_condition && (x<75 && y<250);
}

允许在需要时使用。

if (special_condition(conditions))
    do_something();
else
    do_something_else();

当遇到if时会发生这种情况,但是,当函数仍然被调用时,如果current_condition为false,这将不会发生短路。

答案 4 :(得分:0)

简短回答Stefan,用C ++编号

&=期间评估表达式。

短路表达,例如如果ba等表达式中为a && b,则忽略input { jdbc { jdbc_connection_string => "jdbc:mysql://127.0.0.1:3306/xxx" jdbc_user => "xxx" jdbc_password => "xxx" jdbc_driver_library => "mysql-connector-java-5.1.41.jar" jdbc_driver_class => "com.mysql.jdbc.Driver" schedule => "* * * * *" statement => "SELECT * from a WHERE updated_at > :sql_last_value order by updated_at" use_column_value => true tracking_column => updated_at } output { kafka { codec => plain { format => "%{message}" } topic_id => "mytopic" } file { codec => json_lines path => "/tmp/output_a.log" } } 通常可在您的环境中配置,通常可以配置。

如果您仍希望这样做,请改为创建评估功能。

/安德斯