title: C++ Templated Virtual Function
body: <p>Templated virtual member functions are not supported in C++ but I have a scenario where it would be ideal. Im wondering if someone has ideas for ways to accomplish this.</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  
  class Foo {
  public:
      virtual void bar(int ){}
      // make a clone of my existing data, but with a different policy
      virtual Foo* cloneforDB() = 0;
  };
  
  
  struct DiskStorage {
      static void store(int x) { std::cout &lt;&lt; "DiskStorage:" &lt;&lt; x &lt;&lt; "\n"; }
  };
  
  struct DBStorage {
      static void store(int x) { std::cout &lt;&lt; "DBStorage:" &lt;&lt; x &lt;&lt; "\n"; }
  };
  
  template&lt;typename Storage&gt;
  class FooImpl : public Foo {
  public:
      FooImpl():m_value(0) {}
      template&lt;typename DiffStorage&gt;
      FooImpl(const FooImpl&lt;DiffStorage&gt;&amp; copyfrom) {
          m_value = copyfrom.m_value;
      }
      virtual void bar(int x) {
          Storage::store(m_value);
          std::cout &lt;&lt; "FooImpl::bar new value:" &lt;&lt; x &lt;&lt; "\n";
          m_value = x;
      }
      virtual Foo* cloneforDB() {
          FooImpl&lt;DBStorage&gt; * newfoo = new FooImpl&lt;DBStorage&gt;(*this);
          return newfoo;
      }
      int m_value;
  };
  
  int main()
  {
      Foo* foo1 = new FooImpl&lt;DiskStorage&gt;();
      foo1-&gt;bar(5);
      Foo* foo2 = foo1-&gt;cloneforDB();
      foo2-&gt;bar(21);
  }
  </code></pre>
  
  <p>Now if I want to clone the Foo implmemetation, but with a different Storagepolicy, I have to explicitly spell out each such implementation:</p>
  
  <pre><code>cloneforDB()
  cloneforDisk()
  </code></pre>
  
  <p>A template parameter would have simplified that.
  Can anyone think of a cleaner way to do this?
  Please focus on the idea and not the example, since its obviously a contrived example.</p>