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

时间:2020-03-06 15:00:39  来源:igfitidea点击:

基本上我有以下课程:

class StateMachine {
...
StateMethod stateA();
StateMethod stateB();
...
};

方法stateA()和stateB()应该能够返回指向stateA()和stateB()的指针。
如何键入StateMethod方法?

解决方案

我的理念是不使用原始成员函数指针。我什至不真正知道如何使用原始指针typedef来做你想做的事情,其语法是如此可怕。我喜欢使用boost :: function。

几乎可以肯定这是错误的:

class X
{
  public:
    typedef const boost::function0<Method> Method;

    // some kind of mutually recursive state machine
    Method stateA()
    { return boost::bind(&X::stateB, this); }
    Method stateB()
    { return boost::bind(&X::stateA, this); }
};

这个问题肯定比第一次见到要困难得多

编辑:njsf在这里证明我错了。但是,我们可能会发现静态铸件更易于维护,因此我将其余部分留在这里。

因为完整类型是递归的,所以没有"正确的"静态类型:

typedef StateMethod (StateMachine::*StateMethod)();

最好的选择是使用typedef void(StateMachine :: * StateMethod)();然后执行丑陋的state =(StateMethod)(this-> * state)();`

PS:boost :: function需要一个显式的返回类型,至少从我对文档的阅读来看:boost :: function0 &lt;ReturnType>

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.

仅使用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); }  

};

我永远不会记住可怕的C ++函数declspec,因此,例如,每当我不得不找出描述成员函数的语法时,我只会引起故意的编译器错误,该错误通常为我显示正确的语法。

因此给定:

class StateMachine { 
    bool stateA(int someArg); 
};

stateA的typedef的语法是什么?不知道..所以让我们尝试给它分配一些不相关的东西,看看编译器怎么说:

char c = StateMachine::stateA

编译器说:

error: a value of type "bool (StateMachine::*)(int)" cannot be used to initialize 
       an entity of type "char"

在那里:" bool(StateMachine :: *)(int)"是我们的typedef。