Is it possible to create a C++ factory system that can create an instance of any "registered" object
- by chrensli
Hello,
I've spent my entire day researching this topic, so it is with some scattered knowledge on the topic that i come to you with this inquiry. Please allow me to describe what I am attempting to accomplish, and maybe you can either suggest a solution to the immediate question, or another way to tackle the problem entirely.
I am trying to mimic something related to how XAML files work in WPF, where you are essentially instantiating an object tree from an XML definition. If this is incorrect, please inform. This issue is otherwise unrelated to WPF, C#, or anything managed - I solely mention it because it is a similar concept..
So, I've created an XML parser class already, and generated a node tree based on ObjectNode objects. ObjectNode objects hold a string value called type, and they have an std::vector of child ObjectNode objects.
The next step is to instantiate a tree of objects based on the data in the ObjectNode tree. This intermediate ObjectNode tree is needed because the same ObjectNode tree might be instantiated multiple times or delayed as needed. The tree of objects that is being created is such that the nodes in the tree are descendants of a common base class, which for now we can refer to as MyBase. Leaf nodes can be of any type, not necessarily derived from MyBase.
To make this more challenging, I will not know what types of MyBase derived objects might be involved, so I need to allow for new types to be registered with the factory.
I am aware of boost's factory. Their docs have an interesting little design paragraph on this page:
o We may want a factory that takes some arguments that are forwarded to the constructor,
o we will probably want to use smart pointers,
o we may want several member functions to create different kinds of objects,
o we might not necessarily need a polymorphic base class for the objects,
o as we will see, we do not need a factory base class at all,
o we might want to just call the constructor - without #new# to create an object on the stack, and
o finally we might want to use customized memory management.
I might not be understanding this all correctly, but that seems to state that what I'm trying to do can be accomplished with boost's factory. But all the examples I've located, seem to describe factories where all objects are derived from a base type.
Any guidance on this would be greatly appreciated.
Thanks for your time!