mardi 29 août 2017

How do I call an rvalue member function from another rvalue member function?

I'm trying to create a class that is only supposed to exist temporarily. I'm using this to create an interface similar to the partial application of a function. Here's a silly example of what I'm trying to do.

struct Adder {
  explicit Adder(const int &leftOp)
    : leftOp(leftOp) {}

  int add(const int rightOp) const {
    return leftOp + rightOp;
  }

  //note that addTwice calls add
  int addTwice(const int rightOp) const {
    return add(rightOp) + add(rightOp);
  }

private:
  const int &leftOp;
};

struct Calculator {
  explicit Calculator(const int leftOp)
    : leftOp(leftOp) {}      

  Adder add() const {
    return Adder(leftOp);
  }

  void setLeftOp(const int newLeftOp) {
    leftOp = newLeftOp;
  }

private:
  int leftOp;
};

The calculator is used like this.

Calculator myCalculator(4);
const int myNum = myCalculator.add().add(5);
std::cout << myNum << '\n'; // 9

I want to restrict the interface of Adder so that it can only be called as above. I want the compiler to stop users from storing an Adder in a variable.

auto myCalcPtr = std::make_unique<Calculator>(4);
const Adder adder = myCalcPtr->add();
myCalcPtr.reset();
//oh dear. Adder has a dangling reference to a member in Calculator
const int myNum = adder.add(5);

My immediate thought was to mark Adder::add and Adder::addTwice as && but I got compiler errors in Adder::addTwice. The error was

No matching member function for call to `add`
Candidate function not viable: 'this' argument has type 'const Adder' but method is not marked const

So I added made both functions const && but still got the same error then I came to stackoverflow and asked

How do force all instances of Adder to always be a tempory?

My actual problem is much more complicated than the above example. I'm not a beginner asking about homework!

Aucun commentaire:

Enregistrer un commentaire