5

我正在为一个学校项目用 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);
}
4

4 回答 4

11
std::for_each(
    _instructList.begin(), 
    _instructList.end(), 
    std::bind1st(std::mem_fun(&Chipset::pushInstruction), this));
于 2011-02-19T11:39:16.120 回答
3

当您不记得std::bind函数的语法时,有时编写一个仅转发给成员函数的函子会更容易:

struct PushInstruction {
  PushInstruction(Chipset& self) : self(self) {} 

  void operator()(instructionList* instruction) {
    self.pushInstruction(instruction);
  }    

  Chipset& self;    
};

std::for_each(_instructList.begin(), _instructList.end(), PushInstruction(*this));

一点解释:

我定义了一个类,它在其构造函数中获取我们要调用的对象pushInstruction,并存储对该对象的引用。

然后我定义一个operator()hich 接受你想要推送的指令,然后调用pushInstruction.

for_each循环中,我只是传递this给我的构造函数,创建函子的一个实例,该实例被传递给for_each,然后operator()它为每个元素调用它。

于 2011-02-19T11:44:27.107 回答
2

用作boost::bind

std::for_each(/*..*/, /*..*/,
            boost::bind(&Chipset::pushInstruction, this, _1));
于 2011-02-19T11:29:48.750 回答
2

您可以通过指针获取应用在您的 cpu 上的仿函数bind1stthis

std::foreach( instructList.begin(), instructList.end(),
      std::bind1st
          ( std::mem_fun( &CChipSet::pushInstruction )
          , this 
          )
      );

(注意:我故意把你的下划线去掉_instructionList。这是不允许的。)

于 2011-02-19T11:38:23.853 回答