基本上我有以下类:
class StateMachine {
...
StateMethod stateA();
StateMethod stateB();
...
};
stateA()和stateB()方法应该能够返回指向stateA()和stateB()的指针.
如何typedef的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;
}
This solution has three main
strengths:
It solves the problem as required. Better still,it’s type-safe and
portable.Its machinery is transparent: You get natural Syntax for the
caller/user,and natural Syntax for
the function’s own “return stateA;”
statement.It probably has zero overhead: On modern compilers,the proxy class,with its storage and functions,should inline and optimize away to nothing.