Take a careful look at this:
[source:c]
include
class Gadget { public: void sayHello() const { std::cout << “Gadget!” << std::endl; } };
class Widget { public: void sayHello() const { std::cout << “Widget!” << std::endl; } };
template
template
template class T, class B> class Creator : public T { public: void exec() { B* obj = this->create(); obj->sayHello(); delete obj; } };
typedef Creator
int main (int argc, char * const argv[]) { Manager obj; obj.exec(); return 0; } [/source]
Try changing “MallocCreator” by “OpNewCreator” and “Widget” by “Gadget” in the typedef of line 57, recompile and run; of course you can provide default values, so that
[source:c:firstline(44)] … template class T = MallocCreator, class B = Widget> class Creator : public T … [/source]
so that you just do
[source:c:firstline(56)] … typedef Creator<> Manager; … [/source]
I’ve just started reading “Modern C++ Design” by Andrei Alexandrescu and I’ve already my head spinning out of orbit. This is amazing (and by giving a quick look at the rest of the book, there’s even more incredible stuff there)!