Lets say, I have two Engine classes (based on fuel type e.g Gas or Electric)
template<class Derived>
class ElectricEngine {};
and
template <typename Derived>
class GasEngine {};
Now say I want to make CarEngine
and PlaneEngine
, each of which can choose one of the above base classes. Also I need to do CRTP (static polymorphism). So a straight forward way to do this are as following:
class ElectricCarEngine : public ElectricEngine<ElectricCarEngine> {};
class GasCarEngine : public GasEngine<GasCarEngine> {};
class ElectricPlaneEngine : public ElectricEngine<ElectricPlaneEngine> {};
class GasPlaneEngine : public GasEngine<GasPlaneEngine> {};
The above works, but its lot of redundant code, since my methods of each CarEngine
types i.e ElectricCarEngine
and GasCarEngine
are same. Its the same story for ElectricPlaneEngine
and GasPlaneEngine
.
Assuming something like below compiles :
template <typename Base>
class CarEngineInterface : public Base<CarEngineInterface<Base> > {};
We can then reuse this class to create any CarEngine
Types by simple typedfs.
For example:
typedef CarEngineInterface<ElectricCarEngine> ElectricCarEngine;
typedef CarEngineInterface<GasCarEngine> ElectricCarEngine;
However this fails because of the cyclic dependency. How can I achieve a similar effect?
Is there some traits magic to solve this? (Like the ones used to refer Derived class typedefs from base classes in CRTP)
I am on C++99 but I can use Boost. Also I am a noob in c++ templates.
Let me know if I need to clarify anything.
Ideaone link: https://ideone.com/uMylVY