基本上我有以下课程:
class StateMachine { ... StateMethod stateA(); StateMethod stateB(); ... };
stateA()和stateB()方法应该能够返回指向stateA()和stateB()的指针.如何输入定义StateMethod?
GotW#57表示为此目的使用具有隐式转换的代理类.
struct StateMethod; typedef StateMethod (StateMachine:: *FuncPtr)(); struct StateMethod { StateMethod( FuncPtr pp ) : p( pp ) { } operator FuncPtr() { return p; } FuncPtr p; }; class StateMachine { StateMethod stateA(); StateMethod stateB(); }; int main() { StateMachine *fsm = new StateMachine(); FuncPtr a = fsm->stateA(); // natural usage syntax return 0; } StateMethod StateMachine::stateA { return stateA; // natural return syntax } StateMethod StateMachine::stateB { return stateB; }
该解决方案有三个主要优势:
它根据需要解决了问题.更好的是,它是类型安全和便携式的.
它的机制是透明的:你得到调用者/用户的自然语法,以及函数自己的"return stateA"的自然语法.声明.
它可能没有任何开销:在现代编译器中,代理类及其存储和功能应该内联并优化为零.
仅使用typedef:
class StateMachine { public: class StateMethod; typedef StateMethod (StateMachine::*statemethod)(); class StateMethod { statemethod method; StateMachine& obj; public: StateMethod(statemethod method_, StateMachine *obj_) : method(method_), obj(*obj_) {} StateMethod operator()() { return (obj.*(method))(); } }; StateMethod stateA() { return StateMethod(&StateMachine::stateA, this); } StateMethod stateB() { return StateMethod(&StateMachine::stateB, this); } };