Derived to base implicit pointer type conversion


Keywords:c++ 


Question: 

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)?


1 Answer: 

... especially that the base is abstract and can't be instantiated by itself.

You cannot make Base abstract directly. That needs to derive it from another class (interface) that specifies the pure virtual functions1.


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

No, there isn't.

The typical idiom for the CRTP is to use a static_cast:

 void setRelated() { ptr = static_cast<T*>(this); }

1 Take a look at STTCL where I was using that technique extensively.