title: Store templated class in persistent memory?
body: <p>I want to write information from a template class to a file, and then be able to read from a file to create an instance of that template class. I know how I can write it (use a <code>std::ofstream</code>, write its template parameters and relevant information), but I'm kind of lost on reading it back. I could read the template parameters from the file, but it can't compile that instance of the template class at runtime, so it would fail (or wouldn't compile at all). The reason I want to do this is so I can store something in persistent memory. The class I'm trying to do this for is Eigen's Tensor class, if that helps at all (the example given is more general, and a solution to it would still work). Any ideas on how I can accomplish this?</p>
  
  <p>An example:</p>
  
  <pre><code>template&lt;int example&gt; class A{
      //omitted constructors and everything else
      void write(std::ofstream&amp; out){ //writes relevant information of class to a file
          out&lt;&lt;example;
      }
  };
  </code></pre>
  
  <p>As for reading the file:</p>
  
  <pre><code>void read(std::ifstream&amp; in){
      int example;
      in&gt;&gt;example;
      A&lt;example&gt; a; //doesn't work because A&lt;example&gt; can't be compiled at runtime
  }
  </code></pre>
  
  <p><strong>EDIT:</strong>
  I understand how template classes work, and that they're only compiled if they are used. I also understand why my example doesn't work. My question is if it is possible for me to compile new instances at runtime. I know it is possible to do this with .cpp files (not sure how, I just know it is possible). I don't know if it is possible with template classes, however. My current solution will probably be to make my program create new executables and run those, so they will have the necessary things already compiled, but that is slow and unsatisfactory, so I'm leaving this question up in hopes of getting a better solution.</p>