title: C++ specialize template class function without duplicating code
body: <p>I want to write 5 different classes, each of which has many member functions which are exactly the same, except of one, which is special for each class. Can I write this avoiding code duplication?</p>
  
  <p>Regards,
  Aleksejs</p>
  
  <p>Below is a very shortened version of my code, which throws the error:</p>
  
  <pre><code>template_test.cpp:15:35: error: invalid use of incomplete type ‘class impl_prototype&lt;cl, 1&gt;
  </code></pre>
  
  <hr>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  template &lt;int cl, int dim&gt;
  class impl_prototype {
  public:
    impl_prototype() {}
  
    int f(int x) { return cl + 2 * g(x); }
    int g(int x) { return cl + 1 * x;}
  
  };
  
  template &lt;int cl&gt;
  int impl_prototype&lt;cl, 1&gt;::g(int x) { return cl + 3 * x; }
  
  int main ()
  {
    impl_prototype&lt;0, 0&gt; test_0;
    impl_prototype&lt;0, 1&gt; test_1;
  
  
    cout &lt;&lt; test_0.f(5) &lt;&lt; " " &lt;&lt; test_0.g(5) &lt;&lt; std::endl;
    cout &lt;&lt; test_1.f(5) &lt;&lt; " " &lt;&lt; test_1.g(5) &lt;&lt; std::endl;
  
  
    return 0;
  }
  </code></pre>