c++ - Template base type inheritance -
i have following classes:
class box{...}; class mybox : public box{...};
and template:
template <type t> class objectmanager{...};
which use in other class:
class engine{ objectmanager<box> * manager = nullptr; ... };
then extend (implement) engine
interface:
class myengine : public engine{...}
and in implementation (not earlier!) know manager
should that:
myengine::myengine(){ manager = new objectmanager<mybox>(); }
but gives me error because of types conflict (conversion between objectmanager<box>
, objectmanager<mybox>
), when mybox
inherits box
.
is there way around problem? i don't want modify box
, mybox
, objectmanager
, engine
classes.
templatize engine , inherit myengine engine carrying template instance of box desire. this: (http://codepad.org/szmsbcrb)
#include <iostream> using namespace std; class box{ }; class mybox : public box{ }; template <typename t> class objectmanager{ }; template <typename t> class engine{ public: objectmanager<t*> * manager; }; class myengine : public engine<mybox>{ public: myengine(){ manager = new objectmanager<mybox*>(); cout<<"myengine created"<<endl; } }; int main() { myengine eng = myengine(); return 0; }
the benefit here is, if tomorrow create new box namely mybox2 , want create custom engine myengine2 well, inherit myengine : public engine <mybox2>
. make sure take care of type conversions.
as far remember, in java can declare engine engine<extends t>
lets instantiate engine subtype of template t provided. safer , better way it, not know if c++ provides that.
hope helps.
Comments
Post a Comment