jeudi 29 juin 2017

Derived to base implicit pointer type conversion

For a generic tree structure, I'm using some code that looks like this (The following code is a MCVE):

template <typename T> class Base {
protected:
  Base() {}

public:
  T *ptr;
  void setRelated() { ptr = this; }
};

class Derived : public Base<Derived> {};

int main() {
  Derived d;
  d.setRelated();
  return 0;
}

Rationale: The reason for doing this is to save the developer using this class the effort of having to cast everything around from base to derived and back for every call and algorithm used in this class, especially that the base is abstract and can't be instantiated by itself.

This code doesn't compile. It says:

main.cpp:7: error: invalid conversion from ‘Base<Derived>*’ to ‘Derived*’ [-fpermissive]
   void setRelated() { ptr = this; }
                   ~~~~^~~~~~

The question: Is there a way to make all conversions from Base<Derived>* to Derived* implicit (assuming we shouldn't overload every method)?

Aucun commentaire:

Enregistrer un commentaire