Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ generic object factory by string name
    primarykey
    data
    text
    <p>I need a way to instantiate objects based on its class name passed by as a std::string. This is working right now, but need to be generalized:</p> <pre><code>void* create(std::string name) { if(name == "classOne") return new ClassOne(); else if(name == "classTwo") return new ClassTwo(); /* ... */ } </code></pre> <p><strong>What i do not have</strong>:</p> <ul> <li>Control over the classes to be instantiated: could be thirty party classes. No changes may be done to this classes (i.e. base ancestor, polymorphic creator method, etc...)</li> <li>Full class name listing: more classes could be added later and should not incur in changes to this factory.</li> <li>Wrappers around the classes to be instantiated: As a result of the previous two points.</li> </ul> <p>Anything else is a go.</p> <p>The best use case scenario will be:</p> <pre><code>int main() { void *obj = create("classTree"); // create object based on the string name /* ... */ // once we know by context which specific class we are dealing with ClassTree *ct = (ClassTree*)obj; // cast to appropiate class std::cout &lt;&lt; ct-&gt;getSomeText() &lt;&lt; std::endl; // use object } </code></pre> <p>As a side, and maybe irrelevant note, take in account the object to be instantiated may come from a class or a struct.</p> <p><strong>ADDED INFORMATION</strong></p> <p>I see more context is needed. Here is my particular use case, simplified:</p> <pre><code>// registration mechanism int main() { std::map&lt; std::string, void(*func)(std::string, void*) &gt; processors; // map of processors by class name processors["ClassFour"] = (void(*)(std::string, void*)) &amp;classFourMessageProcessor; // register processor (cast needed from specific to generic) } // function receiving string messages void externalMessageHandler(std::string msg) { std::string objType = extractTypeFromMessageHeader(msg); // extract type from message // now that we know what we are dealing with, create the specific object void *obj = create(objType); // &lt;&lt; creator needed processors[objType](msg, obj); // dispatch message to process } // previously registered message processor void classFourMessageProcessor(std::String msg, ClassFour *obj) { std::string streetAddress = msg.substr(10, 15); // knowing the kind of message we can extract information obj-&gt;moveTheEtherTo(streetAddress); // use the created object } </code></pre> <p><strong>ADDED INFORMATION</strong></p> <p>I am using C++11 with the latest GNU compiler.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload