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>
source
share