class Unit{protected: typedef void (Unit::* PtrFun)(); typedef QMap<int,PtrFun> Operations; Operations operations;public: virtual ~Unit() {} void run(int n){ PtrFun fun=operations.value(n,0); if(fun) (this->*fun)(); }};class Relay : public Unit{public: Relay(){ operations[1] = PtrFun(&Relay::on); operations[2] = PtrFun(&Relay::off); } void on(); void off();};
unit = new Relay(); unit->run(1); unit->run(2);
operations[1] = &Unit::on; operations[2] = &Unit::off;
C++ (Qt)class Unit{protected: typedef QMap<int,std::function> Operations; Operations operations; public: virtual ~Unit() {} void run(int n) { operations[ n ](); }}; class Relay : public Unit{public: Relay(){ operations[1] = std::bind( &Relay::on, this ); operations[2] = std::bind( &Relay::off, this ); } void on(); void off();};