开发者

A stack of function pointers: how to call the function?

I have a stack of function pointers (all of void type & with no parameters). I am having difficulty finding out how I then call/execute a function that is in the stack?

If you look at the simple example below everthing compiles & works except for the last line

typedef class InstructionScreen;
ty开发者_如何转开发pedef void (InstructionScreen::*MemberFuncPtr)();
stack <MemberFuncPtr> instructionStep;              // This is how I declare it. Works
instructionStep.push( &InstructionScreen::step1 );  // This is how I add the member function step(). Works
(*instructionStep.top())();                         // How do I call the function now? This doesn't work

This is the whole code I am attempting to get to compile:

class InstructionScreen
{
     public:
         InstructionScreen()
         {
              instructionStep.push( &InstructionScreen::step1 );
              instructionStep.push( &InstructionScreen::step2 );   

              // add timer to call run instructions each 10 seconds        
         }

         void step1()
         {
         }

         void step2()
         {
         }

         void runInstructions()
         {
              if ( !instructionStep.empty() )
              {
                  *(instructionStep.top())(); 
                  instructionStep.pop();
              }
              // else kill timer
         }

     private:
          stack <MemberFuncPtr> instructionStep;   
};


You need an instance to call a member function. Try this:

InstructionScreen screen;
MemberFuncPtr step = instructionStep.top();
(screen.*step)();

To run a function in the stack from within another member function, you can use:

MemberFuncPtr step = instructionStep.top();
(this->*step)();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜