title: Passing objects of different types with the same interface
body: <p>I have a number of class, all with exactly the same interface.  This interface defines a few methods, some of which are templated (the class itself may or may not be).</p>
  
  <p>So the interface looks something like this</p>
  
  <pre><code>class MyClass
  {
  public:
    void Func1();
  
    template &lt;typename T&gt;
    void Func2(T param);
  };
  </code></pre>
  
  <p>I have a number of functions which take various objects which conform to this interface but want to avoid having to know the exact implementation at compile time.</p>
  
  <p>Obviously, the default C++ solution would be to have a base type that all these classes derive from and pass around a pointer to that and have polymorphism do all the work.</p>
  
  <p>The problem is that templated member functions cannot be virtual so this method cannot be used.  I also want to avoid changing the current set of classes that follow this interface because there are a large number of them, some of which are defined outside the scope of my project.</p>
  
  <p>The other solution is to template the functions that use these objects so they specialise for the right type.  This could be a solution but due to legacy requirements templating a large number functions may not be possible (this is something I cannot do anything about as the client code isn't something I have responsibility for).</p>
  
  <p>My initial thought was to provide some kind of carrier class which is type neutral and in effects wraps the common interface here and has a base interface class to pass around the internal type.  </p>
  
  <p>Something along the lines of </p>
  
  <pre><code>class MyInterface
  {
  public:   
   virtual void Func1() = 0;
  };
  
  template &lt;typename T&gt;
  class MyImplementation
  {
  public:
    virtual void Func1()
    {
      m_impl-&gt;Func1();
    }
  
  private:
    T* m_impl;
  };
  </code></pre>
  
  <p>But again the templated member functions seem to block this approach.</p>
  
  <p>I looked at the boost::any and boost::function classes which I thought might offer some kind of solution but they don't seem to give me the right answer.</p>
  
  <p>So, does anyone have any suggestions or work around on how to make this possible, if indeed it is?  Personally I'm leaning towards having to template the various functions that require these objects - since that's the functionality templates provide - but thought it worth investigating first.</p>
  
  <p>Thanks in advance</p>