Another way is to dynamically register a creator function to a dynamical Factory object.
BluePen *create_BluePen() { return new BluePen; }
static bool BluePen_creator_registered =
Factory::instance()->registerCreator("BluePen",
create_BluePen);
One interesting effect in doing like this is that the static bool variable BluePen-creator-registered will be set prior main() starts thus making the registering automated.
These lines are sometimes made through ordinary macros, ie as
#define METAIMPL( _name ) \
_name *create_ ## _name() { return new _name; } \
static bool _name ## _creator_registered = \
Factory::instance()->registerCreator(# _name, \
create_ ## _name)
...and used close to the constructor
METAIMPL( BluePen ); // auto registers to the Factory
BluePen::BluePen() : Pen() {
// something
}
Then the Factory's task will be to store and lookup these creator functions. I leave the rest as the exercise ;) ie the use of a METADECL macro
If you want more info, see here under chapter 4.1 Meta Information which also includes a method for expanding to include possibilities for inspector features
I learnt this from using ET++ that was a project to port old MacApp to C++ and X11. In the effort of it Eric Gamma etc started to think about Design Patterns
And...(May 7 2011) Finally came around to push an example to github
https://github.com/epatel/cpp-factory