Is it possible to define Boolean expressions that can be evaluated later?

Looking to achieve a kind of dynamic expression, where I can later evaluate the logical expressions if they are called.

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

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

for example, I use the same conditions throughout my code, and it would be easier if I could just adjust one operator or add more to it, even when the programs are running.

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

and then in code

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

edit: conditions should be evaluated in an if statement.

+4
source share
5 answers

Be very careful when working with && and &


Reason 1

Extension of the postulated (and syntactically invalid)

condition &&= condition2;

to

condition = condition && condition2;

: condition2 , condition false.


2

& && , . 0b01 & 0b10 0, 0b01 && 0b10 true ( ++ 14).


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

condition2 , condition true

+2

.


...

[..]

. , (). :

#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

, :

: .

, , ():

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);
}

, .

, , , . .

, , , .

+1

- , , .

,

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 , .

0
source

Stefan's short answer, in C ++ no.

Expression is evaluated on time &=.

Short trailing expressions, for example. ignoring bif afalse in expressions such as a && bis usually configured in your environment and is usually executed.

If you still want to do this, create a rating function.

/ Anders

0
source

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


All Articles