c++ - How to template static factory method? -
how template below code? first, have book base:
class book { public: book() {} ~book() {} }
then computerbook:
class computerbook: public book { public: static computerbook* create() { return new computerbook(); } private: computerbook ():book() {} }
then phonebook:
class phonebook: public book { public: static phonebook* create() { return new phonebook(); } private: phonebook():book() {} }
phonebook has 2 inheritances:
class phonebook1: public phonebook { public: static phonebook1* create() { return new phonebook1(); } private: phonebook1():phonebook() {} } class phonebook2: public phonebook { public: static phonebook2* create() { return new phonebook2(); } private: phonebook2():phonebook() {} }
so can merge computerbook , phonebook1, phonebook2 1 template?
from looks trying do, making static factory method called create
of books. can templatize method this:
class book { public: book() {} ~book() {} template<typename t> static book* create() { return new t(); } }
and make phone book:
book::create<phonebook1>();
also make sure constructors each of books public, or friends of book::create
static method.
Comments
Post a Comment