title: C++ factory of a class that specializes a templated superclass
body: <p>I'm developing a C++ framework for mathematical optimization and I'm struggling to find a good design for my sparse matrix representations.<br />
  Basically:</p>
  <ul>
  <li>I have two sparse matrix representations: types A and B ;</li>
  <li>I have (say) four linear solvers, Alan, Alicia, Beth and Benjamin. Alan and Alicia works exclusively with A matrices, Beth and Benjamin with B matrices ;</li>
  <li>I'd like to template my code so that choosing a linear solver at runtime sets the type of all the matrices (type A or B) in the rest of the code (so that the matrix of the linear system is generated directly in the right format).</li>
  </ul>
  <p>I tried the following (simplified) code:</p>
  <pre><code>template &lt;class MatrixType&gt;
  class LinearSolver {
     virtual void factorize(const MatrixType&amp; matrix) = 0;
  }
  
  class LinearSolverAlan: public LinearSolver&lt;MatrixTypeA&gt; {
     void factorize(const MatrixTypeA&amp; matrix) override;
  }
  
  class LinearSolverAlicia: public LinearSolver&lt;MatrixTypeA&gt; {
     void factorize(const MatrixTypeA&amp; matrix) override;
  }
  
  class LinearSolverBeth: public LinearSolver&lt;MatrixTypeB&gt; {
     void factorize(const MatrixTypeB&amp; matrix) override;
  }
  
  class LinearSolverBenjamin: public LinearSolver&lt;MatrixTypeB&gt; {
     void factorize(const MatrixTypeB&amp; matrix) override;
  }
  </code></pre>
  <p>The common supertype of the solvers is the template type <code>LinearSolver</code>, so I templated the factory as well:</p>
  <pre><code>template&lt;class MatrixType&gt;
  class LinearSolverFactory {
  public:
     std::unique_ptr&lt;LinearSolver&lt;MatrixType&gt; &gt; create(const std::string&amp; solver_name) {
       if (solver_name == &quot;alan&quot;) {
          return std::make_unique&lt;LinearSolverAlan&gt;();
       }
       else if (...) {
          ...
       }
     }
  };
  </code></pre>
  <p>Then on a higher level, I call <code>LinearSolverFactory::create()</code> with the right solver name and template parameter.</p>
  <p>However it won't compile (<code>std::unique_ptr&lt;LinearSolverAlan&gt;</code> cannot be converted to a <code>std::unique_ptr&lt;LinearSolver&lt;MatrixTypeA&gt; &gt;</code>). I'm not good enough at templates to see whether the problem can be fixed.</p>
  <p>Thanks for your help :)</p>
  <p>Charlie</p>