Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement fluent interface with a base class, in C++

Tags:

c++

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.

like image 438
yegor256 Avatar asked May 04 '10 19:05

yegor256


1 Answers

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>
like image 176
Patrick Avatar answered Sep 21 '22 10:09

Patrick