Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's something I do often, it's not pretty, but it's simple and useful.</p> <p>I often work with template containers that implement an interface, imagine something like</p> <pre><code>template&lt;class T&gt; class MyVector : public ContainerInterface ... </code></pre> <p>Where ContainerInterface has basic useful stuff, but that's all. If I want a specific algorithm on vectors of integers without exposing my template implementation, it is useful to accept the interface objects and dynamic_cast it down to MyVector in the implementation. Example:</p> <pre><code>// function prototype (public API, in the header file) void ProcessVector( ContainerInterface&amp; vecIfce ); // function implementation (private, in the .cpp file) void ProcessVector( ContainerInterface&amp; vecIfce) { MyVector&lt;int&gt;&amp; vecInt = dynamic_cast&lt;MyVector&lt;int&gt; &gt;(vecIfce); // the cast throws bad_cast in case of error but you could use a // more complex method to choose which low-level implementation // to use, basically rolling by hand your own polymorphism. // Process a vector of integers ... } </code></pre> <p>I could add a Process() method to the ContainerInterface that would be polymorphically resolved, it would be a nicer OOP method, but I sometimes prefer to do it this way. When you have simple containers, a lot of algorithms and you want to keep your implementation hidden, dynamic_cast offers an easy and ugly solution.</p> <p>You could also look at double-dispatch techniques.</p> <p>HTH</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. This table or related slice is empty.
    1. 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