[C++] Class Member Function 의 저장과 호출
CS/C/C++ 2009. 9. 3. 11:10참조 : Gof Design Pattern
Command 패턴에 나온 예이다
#include <iostream> using namespace std; class Command { public: virtual void Execute() = 0; }; template <class Receiver> class SimpleCommand : public Command { public: typedef void (Receiver::*Action) (); SimpleCommand(Receiver* r, Action a) : _receiver(r), _action(a) {} virtual void Execute(); private: Action _action; Receiver* _receiver; }; template<class Receiver> void SimpleCommand<Receiver>::Execute() { (_receiver->*_action)(); } class MyClass { public: MyClass() {} MyClass(const MyClass &) {} MyClass(const MyClass *) {} void MyAction() { cout << "MyClass Action\n"; } }; int main(void) { MyClass* receiver = new MyClass; Command* aCommand = new SimpleCommand<MyClass>(receiver, &MyClass::MyAction); aCommand->Execute(); }
형정의
typedef void (Receiver::*Action) ();
전달
Action _action = &MyClass::MyAction;
호출
(_receiver->*_action)();
후아...