Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can do it with a template.</p> <p>Edit: new implementation based on the extra information. If <code>mymap</code> is a <code>std::map&lt;int, Shape*&gt;</code>:</p> <pre><code>template &lt;typename T&gt; void lookup(int idNum, T* &amp;ptr) { auto it = mymap.find(idNum); if (it == mymap.end()) { ptr = 0; } else { ptr = dynamic_cast&lt;T*&gt;(*it); // Shape must have a virtual member function } } </code></pre> <p>Or you might prefer:</p> <pre><code>template &lt;typename T&gt; T* lookup(int idNum) { auto it = mymap.find(idNum); if (it == mymap.end()) { return 0; } return dynamic_cast&lt;T*&gt;(*it); } </code></pre> <p>Then call it like <code>Circle *circle = database.lookup&lt;Circle&gt;(123);</code></p> <p>Obviously polymorphic containers are a whole heap of fun in themselves, but I'll assume you have that sorted. There may well be a <code>shared_ptr</code> in there somewhere that I've left out.</p> <p>Old implementation when I thought the DB might store copies of POD:</p> <pre><code>template &lt;typename T&gt; void lookup(int idNum, T* &amp;ptr) { void *theresult = // something based on idNum // some check needed here that theresult really is the right type. // how you do this depends on the database, but suppose that // the database gives us some integer "type" which indicates the type if (type != type_constant&lt;T&gt;::value) { ptr = 0; } else { ptr = static_cast&lt;T*&gt;(theresult); } } </code></pre> <p>type_constant is an example of "type traits", you implement it like:</p> <pre><code>template &lt;typename T&gt; struct type_constant {}; template &lt;&gt; struct type_constant&lt;Circle&gt; { static const int value = 1; }; template &lt;&gt; struct type_constant&lt;Rectangle&gt; { static const int value = 2; }; // etc... </code></pre>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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