Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Using something like <a href="http://www.boost.org/doc/libs/1_41_0/libs/serialization/doc/index.html" rel="noreferrer">Boost Serialization</a>, while by no means a standard, is a (for the most part) very well written library that does the grunt work for you.</p> <p>The last time I had to manually parse a predefined record structure with a clear inheritance tree, I ended up using the <a href="http://en.wikipedia.org/wiki/Factory_pattern" rel="noreferrer">factory pattern</a> with registrable classes (i.e. Using a map of key to a (template) creator function rather than a lot of switch functions) to try and avoid the issue you were having.</p> <p><strong>EDIT</strong><br> A basic C++ implementation of a object factory mentioned in the above paragraph.</p> <pre><code>/** * A class for creating objects, with the type of object created based on a key * * @param K the key * @param T the super class that all created classes derive from */ template&lt;typename K, typename T&gt; class Factory { private: typedef T *(*CreateObjectFunc)(); /** * A map keys (K) to functions (CreateObjectFunc) * When creating a new type, we simply call the function with the required key */ std::map&lt;K, CreateObjectFunc&gt; mObjectCreator; /** * Pointers to this function are inserted into the map and called when creating objects * * @param S the type of class to create * @return a object with the type of S */ template&lt;typename S&gt; static T* createObject(){ return new S(); } public: /** * Registers a class to that it can be created via createObject() * * @param S the class to register, this must ve a subclass of T * @param id the id to associate with the class. This ID must be unique */ template&lt;typename S&gt; void registerClass(K id){ if (mObjectCreator.find(id) != mObjectCreator.end()){ //your error handling here } mObjectCreator.insert( std::make_pair&lt;K,CreateObjectFunc&gt;(id, &amp;createObject&lt;S&gt; ) ); } /** * Returns true if a given key exists * * @param id the id to check exists * @return true if the id exists */ bool hasClass(K id){ return mObjectCreator.find(id) != mObjectCreator.end(); } /** * Creates an object based on an id. It will return null if the key doesn't exist * * @param id the id of the object to create * @return the new object or null if the object id doesn't exist */ T* createObject(K id){ //Don't use hasClass here as doing so would involve two lookups typename std::map&lt;K, CreateObjectFunc&gt;::iterator iter = mObjectCreator.find(id); if (iter == mObjectCreator.end()){ return NULL; } //calls the required createObject() function return ((*iter).second)(); } }; </code></pre>
 

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