samedi 24 septembre 2016

Chain-calling member functions off a constructor of a named object

First, I'm NOT talking about c++11 constructor chaining aka constructor delegation.

Class member functions can return a reference to itself (the class) so function calls can be chained. (Such as how the cout << operator works to allow chain calls.)

When instantiating an anonymous object, such chain calls can occur off the constructor.

Can chain calls be made off a constructor of a named object? The lines for "foo a" and "foo b" below do not compile, so I'm wondering if there's a different syntax.

#include <iostream>
using namespace std;

class foo {
   public:
      foo(int x) : val{x} { };
      foo& inc() { ++val; return *this; }
      int getVal() { return val; };
   private:
      int val;
};

int main() {
   cout << foo(1).inc().getVal() << endl; // prints 2
   cout << foo{2}.inc().inc().inc().inc().getVal() << endl; // prints 6
   foo a(3).inc(); // error: expected ‘,’ or ‘;’ before ‘.’ token
   foo b{4}.inc(); // error: expected ‘,’ or ‘;’ before ‘.’ token
   cout << a.getVal() << endl;
   cout << b.getVal() << endl;
}

Aucun commentaire:

Enregistrer un commentaire