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:
template <typename T>
class Base {
public:
T& add(int x) {
return *static_cast<T *>(this);
}
}
Then inherit Derived from Base like this:
class Derived : public Base<Derived>
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:
template <typename T>
class Intermediate : public Base {
public:
T& add(int x) {
Base::add(x);
return *static_cast<T *>(this);
}
}
And let Derived inherit from Intermediate:
class Derived : public Intermediate<Derived>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With