title: How to implement template class covariance in C++?
body: <p>Is it possible to implement a class template in such a way that one object could be casted to another if their template arguments are related? Here is an exaple to show the idea (of course it will not compile):</p>
  
  <pre><code>struct Base {};
  struct Derived : Base {};
  
  template &lt;typename T&gt; class Foo {
      virtual ~Foo() {}
      virtual T* some_function() = 0;
  };
  
  Foo&lt;Derived&gt;* derived = ...;
  Foo&lt;Base&gt;* base = derived;
  </code></pre>
  
  <p>The additional problem here is that Foo is an abstract class used as an interface containing functions returning T&amp; and T*, so I can't implement a template copy constructor.</p>
  
  <p>I'm writing a universal Iterator class which can hold any STL iterator, and in addition to type erasure I'd like it to be polymorphic, i.e. I could write something like this:</p>
  
  <pre><code>std::list&lt;Derived&gt; l;
  MyIterator&lt;Base&gt; it(l.begin());
  </code></pre>
  
  <p>UPD: That was my mistake, I didn't actually need casting Foo* to Foo* to implement MyIterator, so I think the question is not actual anymore.</p>