Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>While it is possible to cast to <code>void *</code> and back, the problem is knowing which type you're popping. After all, you give the example:</p> <pre><code>Container&lt;string&gt; b = *reinterpret_cast&lt;Container&lt;string&gt;*&gt;(_collection.pop()); Container&lt;int&gt; a = *reinterpret_cast&lt;Container&lt;int&gt;*&gt;(_collection.pop()); </code></pre> <p>However, if you were to accidentally do:</p> <pre><code>Container&lt;int&gt; a = *reinterpret_cast&lt;Container&lt;int&gt;*&gt;(_collection.pop()); Container&lt;string&gt; b = *reinterpret_cast&lt;Container&lt;string&gt;*&gt;(_collection.pop()); </code></pre> <p>Now you've got pointers to the wrong type, and will likely see crashes - or worse.</p> <p>If you want to do something like this, <em>at least</em> use <code>dynamic_cast</code> to check that you have the right types. With <code>dynamic_cast</code>, you can have C++ check, at runtime (using <a href="http://en.wikipedia.org/wiki/Run-time_type_information" rel="nofollow">RTTI</a>), that your cast is safe, as long as the types being casted (both before and after) have a common base type with at least one virtual method.</p> <p>So, first create a common base type with a virtual destructor:</p> <pre><code>class ContainerBase { public: virtual ~ContainerBase() { } }; </code></pre> <p>Make your containers derive from it:</p> <pre><code>template &lt;typename T&gt; class Container : public ContainerBase { // ... } </code></pre> <p>Now use a <code>std::stack&lt;ContainerBase *&gt;</code>. When you retrieve items from the stack, use <code>dynamic_cast&lt;Container&lt;int&gt; &gt;(stack.pop())</code> or <code>dynamic_cast&lt;Container&lt;string&gt; &gt;(stack.pop())</code>; if you have the types wrong, these will check, and will return NULL.</p> <p>That said, heterogeneous containers are almost always the wrong thing to be using; at some level you need to know what's in the container so you can actually <em>use</em> it. What are you actually trying to accomplish by creating a container like this?</p>
    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. 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.
    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