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++类中,有6个默认成员函数: 构造函数 析构函数 拷贝...
#pragma once // 1. 设计一个不能被拷贝的类/* 解析:拷贝只会放生在两个场景中:拷贝构造函数以及赋值运...
C类型转换 C语言:显式和隐式类型转换 隐式类型转化:编译器在编译阶段自动进行,能转就转,不能转就编译...
//异常的概念/*抛出异常后必须要捕获,否则终止程序(到最外层后会交给main管理,main的行为就是终止) try...
#pragma once /*Smart pointer 智能指针;灵巧指针 智能指针三大件//1.RAII//2.像指针一样使用//3.拷贝问...
目录<future>future模板类成员函数:promise类promise的使用例程:packaged_task模板类例程...