title: Pimpl idiom as template base class
body: <p>I'm currently researching the <strong>pimpl idiom</strong> and there are very nice tutorials how it could be implement (e.g. <a href="http://oliora.github.io/2015/12/29/pimpl-and-rule-of-zero.html" rel="nofollow noreferrer">here</a>). But i have never seen it implemented as a base template class like this:</p>
  
  <pre><code>#ifndef PIMPL_H
  #define PIMPL_H
  
  template &lt;class T&gt;
  class Pimpl
  {
  public:
      explicit Pimpl();
      explicit Pimpl(T *ptr);
      virtual ~Pimpl() = 0;
  
      Pimpl(const Pimpl&lt;T&gt; &amp;other);
      Pimpl &amp;operator=(const Pimpl&lt;T&gt; &amp;other);
  
  protected:
      T *d_ptr;
  };
  
  template&lt;class T&gt;
  Pimpl&lt;T&gt;::Pimpl() : d_ptr(new T)
  {
  
  }
  
  template&lt;class T&gt;
  Pimpl&lt;T&gt;::Pimpl(T *ptr) : d_ptr(ptr)
  {
  
  }
  
  template&lt;class T&gt;
  Pimpl&lt;T&gt;::~Pimpl()
  {
      delete d_ptr;
      d_ptr = 0;
  }
  
  template&lt;class T&gt;
  Pimpl&lt;T&gt;::Pimpl(const Pimpl&lt;T&gt; &amp;other) : d_ptr(new T(*other.d_ptr))
  {
  
  }
  
  template&lt;class T&gt;
  Pimpl&lt;T&gt; &amp;Pimpl&lt;T&gt;::operator=(const Pimpl&lt;T&gt; &amp;other)
  {
      if (this != &amp;other) {
          delete d_ptr;
          d_ptr = new T(*other.d_ptr);
      }
  
      return *this;
  }
  
  #endif // PIMPL_H
  </code></pre>
  
  <p>Which then could be used in any class you like to pimpl:</p>
  
  <pre><code>#ifndef OBJECT_H
  #define OBJECT_H
  
  #include "pimpl.h"
  
  class ObjectPrivate;
  
  class Object : public Pimpl&lt;ObjectPrivate&gt;
  {
  public:
      Object();
      virtual ~Object();
  
      /* ... */
  };
  
  #endif // OBJECT_H
  </code></pre>
  
  <p>Currently i'm using it in a small example project (build as a shared library) and the only problem i had, was that MSVC warns about the missing destructor for ObjectPrivate (see <strong>C4150</strong>). This warning only occurs, because ObjectPrivate is forward declared and therefore not visible to the delete operator in <strong>Pimpl::~Pimpl()</strong> at compile time.</p>
  
  <p><strong>Does anyone see any sort of problems with this approach?</strong> :-)</p>
  
  <hr>
  
  <p>So there is a now a <strong><a href="https://github.com/0x2648/pimpl-template/blob/master/core/include/pimpl.h" rel="nofollow noreferrer">final version</a></strong> based on the discussion below on GitHub (big thanks to <strong>StoryTeller</strong>). The <a href="https://github.com/0x2648/pimpl-template" rel="nofollow noreferrer">repository</a> also contains a simple usage example.</p>