title: Compile time vs run time polymorphism in C++ advantages/disadvantages
body: <p>In C++ when it is possible to implement the same functionality using either run time (sub classes, virtual functions) or compile time (templates, function overloading) polymorphism, why would you choose one over the other?</p>
  
  <p>I would think that the compiled code would be larger for compile time polymorphism (more method/class definitions created for template types), and that compile time would give you more flexibility, while run time would give you "safer" polymorphism (i.e. harder to be used incorrectly by accident).</p>
  
  <p>Are my assumptions correct? Are there any other advantages/disadvantages to either? Can anyone give a specific example where both would be viable options but one or the other would be a clearly better choice?</p>
  
  <p>Also, does compile time polymorphism produce faster code, since it is not necessary to call functions through vtable, or does this get optimized away by the compiler anyway?</p>
  
  <p>Example:</p>
  
  <pre><code>class Base
  {
    virtual void print() = 0;
  }
  
  class Derived1 : Base
  {
    virtual void print()
    {
       //do something different
    }
  }
  
  class Derived2 : Base
  {
    virtual void print()
    {
      //do something different
    }
  }
  
  //Run time
  void print(Base o)
  {
    o.print();
  }
  
  //Compile time
  template&lt;typename T&gt;
  print(T o)
  {
    o.print();
  }
  </code></pre>