title: Dyamic vs Static Polymorphism in C++ : which is preferable?
body: <p>I understand that dynamic/static polymorphism depends on the application design and requirements. However, is it advisable to ALWAYS choose static polymorphism over dynamic if possible? In particular, I can see the following 2 design choice in my application, both of which seem to be advised against:</p>
  
  <ol>
  <li><p>Implement Static polymorphism using CRTP: No vtable lookup overhead while still providing an interface in form of template base class. But, uses a Lot of switch and static_cast to access the correct class/method, which is hazardous</p></li>
  <li><p>Dynamic Polymorphism: Implement interfaces (pure virtual classes), associating lookup cost for even trivial functions like accessors/mutators</p></li>
  </ol>
  
  <p>My application is very time critical, so am in favor of static polymorphism. But need to know if using too many static_cast is an indication of poor design, and how to avoid that without incurring latency.</p>
  
  <p>EDIT: Thanks for the insight. Taking a specific case, which of these is a better approach?</p>
  
  <pre><code>class IMessage_Type_1
  {
    virtual long getQuantity() =0;
  ...
  }
  class Message_Type_1_Impl: public IMessage_Type_1
  {
    long getQuantity() { return _qty;}
  ...
  }
  </code></pre>
  
  <p>OR</p>
  
  <pre><code>template &lt;class T&gt;
  class TMessage_Type_1
  {
    long getQuantity() { return static_cast&lt;T*&gt;(this)-&gt;getQuantity(); }
  ...
  }
  class Message_Type_1_Impl: public TMessage_Type_1&lt;Message_Type_1_Impl&gt;
  {
    long getQuantity() { return _qty; }
  ...
  }
  </code></pre>
  
  <p>Note that there are several mutators/accessors in each class, and I do need to specify an interface in my application. In static polymorphism, I switch just once - to get the message type. However, in dynamic polymorphism, I am using virtual functions for EACH method call. Doesnt that make it a case to use static poly? I believe static_cast in CRTP is quite safe and no performance penalty (compile time bound) ?</p>