C++ for_each中的成员函数指针

Ole*_*ade 5 c++ foreach member-functions

我正在为一个学校项目开发一个C++的小型虚拟机,它应该像dc命令一样工作,由一个输出输出元素,一个芯片组,一个Cpu和Ram组成.我目前正在研究芯片组,我已经实现了一个小的解析类,以便能够从标准输入或文件中获取一些Asm指令,然后将此指令推送到Cpu.

问题是:我的指令在std :: list中排序,我希望能够通过foreach指令逐个推送它们.为此,我需要能够将我的成员函数"push_instruction"称为for_each的函数指针F; 我无法找到这样做的伎俩......

有任何想法吗?这是我的代码:

/*
** Function which will supervise
** the lexing and parsing of the input (whether it's std_input or a file descriptor)
** the memory pushing of operands and operators
** and will command the execution of instructions to the Cpu
*/
void                    Chipset::startExecution()
{
    /*
    ** My parsing 
    ** Instructions
    **
    */

    for_each(this->_instructList.begin(), this->_instructList.end(), this->pushInstruction);
}


void                    Chipset::pushInstruction(instructionList* instruction)
{
    if (instruction->opCode == PUSH)
      this->_processor->pushOperand(instruction->value, Memory::OPERAND, Memory::BACK);
    else if (instruction->opCode == ASSERT)
      this->_processor->pushOperand(instruction->value, Memory::ASSERT, Memory::BACK);
    else
      this->_processor->pushOperation(instruction->opCode);
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*rik 11

std::for_each(
    _instructList.begin(), 
    _instructList.end(), 
    std::bind1st(std::mem_fun(&Chipset::pushInstruction), this));
Run Code Online (Sandbox Code Playgroud)

  • mem_fun从函数指针创建一个仿函数,operator()期望一个指向正确对象类型的指针作为第一个参数.然后bind1st创建一个functor,它将传递的"this"绑定到第一个参数.所以for_each调用bind1st仿函数传递一个instructionList*,然后这个仿函数调用mem_fun仿函数传递你的"this"然后传递instructionList*. (2认同)