C ++中构造函数中dot <function name =“”>的含义

时间:2015-12-03 03:47:12

标签: c++ llvm

我正在研究LLVM并找到了一段有趣的代码

  case ARM::BMOVPCRX_CALL: {
    EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
      .addReg(ARM::LR)
      .addReg(ARM::PC)
      // Add predicate operands.
      .addImm(ARMCC::AL)
      .addReg(0)
      // Add 's' bit operand (always reg0 for this)
      .addReg(0));

    EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
      .addReg(ARM::PC)
      .addReg(MI->getOperand(0).getReg())
      // Add predicate operands.
      .addImm(ARMCC::AL)
      .addReg(0)
      // Add 's' bit operand (always reg0 for this)
      .addReg(0));
    return;
  }

我的问题是关于.addReg.addImm。我不会说我是C ++的新手,但我从未见过这种类型的代码。它是什么意思,它有什么作用?为什么有人想做这样的事情?

1 个答案:

答案 0 :(得分:11)

这种编写软件的模式称为'method chaining' or the 'named parameter idiom'

例如,您可能有一个班级:

class Example {
    int a, b;

public:
    Example &a(int const a) {this->a = a; return *this;}
    Example &b(int const b) {this->b = b; return *this;}
};

int main(void) {
    Example example;
    example.a(5).b(6); //example.a is now 5, example.b is now 6
    return 0;
}

对于这个例子,应该注意的是,没有什么可以阻止你调用example.b(6).a(5)来获得相同的结果。