c – 如何typedef一个指向方法的指针,返回一个指针的方法?

前端之家收集整理的这篇文章主要介绍了c – 如何typedef一个指向方法的指针,返回一个指针的方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
基本上我有以下类:
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:

  1. It solves the problem as required. Better still,it’s type-safe and
    portable.

  2. Its machinery is transparent: You get natural Syntax for the
    caller/user,and natural Syntax for
    the function’s own “return stateA;”
    statement.

  3. It probably has zero overhead: On modern compilers,the proxy class,with its storage and functions,should inline and optimize away to nothing.

猜你在找的C&C++相关文章