title: using dynamic_cast with templates
body: <p>while implementing a template-based factory in C++, i have created the following <code>allocator</code> function to instantiate a given child class:</p>
  
  <pre><code>template&lt;class ChildClass, class ParentClass&gt;
  ParentClass* allocator() {
     ChildClass *child  = new ChildClass();
     ParentClass*parent = dynamic_cast&lt;ParentClass*&gt;(child);
     if(NULL==parent) {
       delete child;
       return NULL;
     }
     return parent;
  }
  </code></pre>
  
  <p>everything works fine, but when running the code through static code-analysis tools like <a href="http://www.coverity.com/" rel="nofollow">coverity</a>, the <code>delete child;</code> line is flagged as <em>logically dead code</em>.</p>
  
  <p>the reason why i do the runtime-check is to assert, that <code>ChildClass</code> is derived from <code>ParentClass</code>.</p>
  
  <p>now i understand, that during template expansion the compiler already knows whether <code>ChildClass</code> is derived from <code>ParentClass</code>, and that the <code>dynamic_cast</code> is only evaluated during run-time.</p>
  
  <p>so the run-time check is logically dead code, if the <code>ChildClass</code> is indeed derived from the <code>ParentClass</code> (in which case the <code>dynamic_cast</code> will always return <code>non-NULL</code> if <code>ChildClass</code> has been successfully allocated).</p>
  
  <p><strong>but</strong> is there a way to ensure that <code>ChildClass</code> is derived from <code>ParentClass</code> during compile-time (template expansion time)?</p>
  
  <p>afaik, templates and inheritance are unrelated in C++, but i might be missing something obvious.</p>
  
  <h2>restrictions</h2>
  
  <p>unfortunately the code should compile on older compilers (e.g. the C++-implementation that comes with <em>Visual Studio 6</em>) which rules out any newer extension like <code>C++11</code>-features</p>