c++ - Can I create class factory for a constructor with parameter? -


i using class factory create objects dynamically. used answer simplicity (and because using qt).

but realize must add argument constructor

item(bool newitem /* = true*/); 

instead of

item(); 

for code in referred answer:

template <typename t> class classfactory { public:     template <typename tderived>     void registertype(qstring shape)     {         _createfuncs[shape] = &createfunc<tderived>;     }         t* create(qstring shape)     {         typename qmap<qstring, pcreatefunc>::const_iterator = _createfuncs.find(shape);         if (it != _createfuncs.end())         {             return it.value()();         }         return null;     }     private:     template <typename tderived>     static t* createfunc()     {         return new tderived();     }     typedef t* (*pcreatefunc)();     qmap<qstring, pcreatefunc> _createfuncs; }; 

i registered class

classfactory.registertype <type1_item> ("type1"); 

when needed, called

item* item = classfactory.create("type1"); 

i trying add additional argument in class factory, represent constructor argument, attempts result in error.

why need : simple case:

  • create new object - sets defaults; objects, requires open file dialog since data has loaded file.

  • load object - fills data, including filename objects contain file info

to able call "load" function, object must exist - means if create new object, trigger open file dialog though not need it.

the work around see is, have constructor followed setup function. but... means constructing object requires 2-function call, seems bad design.

that why looking way register , call classes using simple calls like

classfactory.registertype <type1_item> ("type1", bool); item* item = classfactory.create("type1", true); 

is possible, , how can ?

you may use modified version

template <typename t, typename ... ts> class classfactory { public:     template <typename tderived>     void registertype(qstring shape)     {         _createfuncs[shape] = &createfunc<tderived>;     }         t* create(qstring shape, ts... args)     {         typename qmap<qstring, pcreatefunc>::const_iterator = _createfuncs.find(shape);         if (it != _createfuncs.end())         {             return it.value()(args...);         }         return nullptr;     }     private:     template <typename tderived>     static t* createfunc(ts... args)     {         return new tderived(args);     }     typedef t* (*pcreatefunc)(ts...);     qmap<qstring, pcreatefunc> _createfuncs; }; 

and use it

classfactory<item, bool> classfactory; classfactory.registertype <type1_item> ("type1");  item* item = classfactory.create("type1", true); 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -