How can I implement this fluent interface in C++:
class Base {
public:
Base& add(int x) {
return *this;
}
}
class Derived : public Base {
public:
Derived& minus(int x) {
return *this;
}
}
Derived d;
d.add(1).minus(2).add(3).minus(4);
Current code doesn’t work since Base class doesn’t know anything about Derived class, etc. I would be very thankful for a hint/suggestion.
Make Base class templated. Use the wanted return type of Base the template type, like this:
Then inherit Derived from Base like this:
Alternatively (as an answer to Noah’s comment), if you don’t want to change Base, you could use an intermediate class that performs the casting, like this:
And let Derived inherit from Intermediate: