简体   繁体   中英

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;
typedef 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)();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM