c++ - Using templates for a factory method on derived classes -


i have base class of there many derived classes. pointers base class stored in containers in program can iterate through , call virtual functions on them.

i have class adds base class pointers container, when derived classes newed (not nude) must return or stored base class pointer.

i thinking making simple base class factory method me, using templates:

    template<class t> //t derived class     static t* factory(){        return static_cast<t*>(functionthataddsbaseclasspointertocontainer(new t));     } 

i see 2 main pros/cons:

advantage: don't need override every derived class

disadvantage: used incorrectly passing t class type not derived base.

is there way ensure t derived inside function factory? or can expect compiler catch instances t not derived?

is general approach acceptable idea, or there better alternative?

is there way ensure t derived inside function factory?

if functionthataddsbaseclasspointertocontainer takes base* done.

base* functionthataddsbaseclasspointertocontainer(base* b);  // <--   template<class t> //t derived class static t* factory(){    // if t not derived base, following line fails compile:    return static_cast<t*>(functionthataddsbaseclasspointertocontainer(new t)); } 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -