Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>maybe the following aproach with a lokup table will be a nice solution.</p> <p>(Note: I don't know wich compiler are you using, so this solution is for c++03, you could take unordered_map instead map if you are using a compiler with c++11 support)</p> <p>(Note 2: You could use smart pointers too, and take care of the returns values, whit this example I only wants to show an aproach)</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;map&gt; #include &lt;vector&gt; struct ClassMaker { virtual void* getInstance() const = 0; virtual ~ClassMaker() {} }; class Factory { private: std::map&lt;std::string, ClassMaker*&gt; lokupTable; typedef typename std::map&lt;std::string, ClassMaker*&gt;::iterator Iterator; public: void addClass(const std::string&amp; key, ClassMaker* const newClassMaker) { lokupTable[key] = newClassMaker; } void* create(const std::string&amp; key) { void* result = NULL; Iterator it = lokupTable.find(key); if(it != lokupTable.end()) result = (it-&gt;second)-&gt;getInstance(); return result; } void releaseTable() { for (Iterator it = lokupTable.begin(); it != lokupTable.end(); ++it) delete it-&gt;second; } }; struct IntCreator : public ClassMaker { void* getInstance() const { return new int; } }; struct StringCreator : public ClassMaker { void* getInstance() const { return new std::string; } }; int main() { Factory myFactory; myFactory.addClass("int", new IntCreator); myFactory.addClass("string", new StringCreator); int* myInt = reinterpret_cast&lt;int*&gt;(myFactory.create("int")); *myInt = 10; std::cout&lt;&lt; *myInt &lt;&lt; std::endl; delete myInt; myFactory.releaseTable(); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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