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

How can I implement this free 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);

The current code does not work, because the base class knows nothing about the Derived class, etc. I would really appreciate a tip / suggestion.

+5
source share
3 answers

Make the base template a template. Use the required return type. Base Type of the template, for example:

template <typename T>
class Base {
public:
  T& add(int x) {
    return *static_cast<T *>(this);
  }
}

Then inherit Derived from Base as follows:

class Derived : public Base<Derived>

Alternatively (as an answer to Noah's comment), if you do not want to change Base, you can use an intermediate class that performs casting, for example:

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>
+10
source

++ . () , , , .

(), .

+1

The problem is your function

  Base& add(int x); 

This is similar to the + = () operator, which also needs to be redefined to run smoothly.

You need to override this function in a derived class.

class Derived : public Base {
public:
  Derived& minus(int x) {
    return *this;
  }
  Derived & add(int x) {
    return  static_cast<Derived &>(this->Base::add(x));
  }
}

thus d.add (1) will return a link to d.

+1
source

All Articles