C ++ evaluates bool variable value dynamically

Situation: I am trying to implement two classes, one of which is called "special". specialhas a member variable bool conditionsand method perform_special. Another class has a name managerand has a type as a member variable special. I want to managercall perform_specialin a member specialonly if conditiontrue.

So far I have implemented this piece of code:

#include<iostream>
using namespace std;

class special{
  public:
    special(){};
    void perform_special();
    void set_conditions( bool cond );
    bool get_conditions();
  private:
    bool conditions;
};
void special::perform_special(){ cout<<"special performed."<<endl; }
void special::set_conditions( bool cond ){ conditions = cond; }
bool special::get_conditions(){ return conditions; }

class manager{
  public:
    manager(){};
    void check_specials();
    void set_effect( special* eff );
  private:
    special* effect;
};
void manager::check_specials(){
  if(effect->get_conditions()){ effect->perform_special(); }
}
void manager::set_effect( special *eff ){ effect = eff; }

int main(){
  int a=3; int b=2;
  bool cond = a<b;
  special effect1;
  effect1.set_conditions( cond );

  a=2; b=3;
  manager manager1;
  manager1.set_effect( &effect1 );
  manager1.check_specials();

  return 0;
}

, : cond, false, a<b . , . check_special , , cond .

: , cond . , a be , , a<b. , cond check_specials() a b?

: , "" , , . "manager" - - -, .. "" manager, , manager , , , .

+4
2

Cond, :

struct Cond
{
    int& a;
    int& b;
    operator bool() const {return a < b;}
};

Cond cond{a, b};

Cond.

if (cond) , a b .

, . - , , std::reference_wrapper.

+2

bool cond(), . , , bool:

class special{
  public:
      using predicate = std::function<bool()>;

      void set_conditions( predicate p );
      ...
};

, , .., :

int main()
{
  int a=3; int b=2;
  auto cond = [&]{ return a<b; };
  special effect1;
  effect1.set_conditions( cond );
  ...
}
+1

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


All Articles