Template class member function pointer usage

xiaoxiao2021-03-06  1

Objective: Create a class to manage the processing of a series of events. Or based on the current status to call different status processing functions. Of course, this feature can be implemented by simple Switch. But use Switch's implementation is not high, it is not easy to maintain, and There is no good adaptability for changes in the demand, which is not good for the code. The following is an example of using the Switch implemented according to but the pre-status call different processing functions: Class Robot {public: Virtual Void Update (unsigned Elapsed) {switch (m_ICURSTATE) {case E_STATE00: DOSTATE00 (); Break; Case E_STATE01: DOSTATE01 (); Break; Default: Break;} void dostate00 (); void dostate01 (); void dostate01 ();} protected: int m_ICURSTATE;} a better implementation method generating state is a mapping function doState This facilitates maintenance of the code is higher efficiency improvements: template class Robot {public: virtual void Update (unsigned elapsed); protected:... virtual void ConstructStateDealMap (void); protected: int m_iCurState; ActionStrategy m_AStrategy; typedef void (CRobot :: * funStateDeal) (void); // This is a 'state to deal function' map typedef map StateDealMap; StateDealMap m_mapStateDeal; private:m_icurElapsed;} void CRobot :: ConstructStateDealMap (void) {m_mapStateDeal.insert (make_pair (e_State00, CRobot :: DoIdle)); m_mapStateDeal.insert (make_pair (e_State01, CRobot :: DoMove));} void CRobot < class ActionStrategy> :: Update (unsigned elapsed) {// Here used the biSearch to find the state deal function m_icurElapsed = elapsed; StateDealMap :: const_iterator cit = m_mapStateDeal.find (m_iCurState);! if (cit = m_mapStateDeal.end () ) {Funstatedeal pfun = cit-> second; (this -> * pfun) ();

转载请注明原文地址: http://www.9cbs.com/read-68200.html

New Post(0)