title: Serializing polymorphic classes with environment-specific state
body: <p>I have some classes that look roughly like this:</p>
  
  <pre><code>class Base {
  public:
      virtual ~Base() {}
      ...
  };
  
  class Derived1 {
      OuterState1&amp; outerState;
      InnerState1 innerState;
      ...
      template &lt;typename Ar&gt;
      void serialize(Ar&amp; ar, const unsigned int /*version*/) {
          ar &amp; innerState;
      }
  public:
      Derived1(OuterState1&amp; outerState) : outerState(outerState) {}
      ...
  };
  
  class Derived2 {
      OuterState2&amp; outerState;
      InnerState2 innerState;
      ...
      template &lt;typename Ar&gt;
      void serialize(Ar&amp; ar, const unsigned int /*version*/) {
          ar &amp; innerState;
      }
  public:
      Derived1(OuterState2&amp; outerState) : outerState(outerState) {}
      ...
  };
  </code></pre>
  
  <p>Basically, the classes have a state that depends on the outside environment, and I don't want to serialize it. This state may be different for the different subclasses. I want to serialize this class. A good thing is that boost::serialization handles polymorphic classes well, but it seems to me that not well enough for me. I could find the following ways to serialize these objects, neither which I like:</p>
  
  <ol>
  <li><p>Use global variables for the outer state. Now either we use these global variables inside the class, or overload <code>load_construct_data()</code> and create the objects from this global variable. The problem with this solution is that it requires global variables, which is generally a bad design, and breaks if the program needs to handle more than one such states.</p></li>
  <li><p>Do not use the polymorphic serialization feature of Boost. Instead, save the actual type in an enum, then save the object non-polymorphically. When loading, load the type enum, then in a switch create the object of the appropriate type with the appropriate outer state, then load the object non-polymorphically. The problem with this is that I have to do a lot of manual coding that would automagically be done by Boost, and that it doesn't work if I want to serialize a collection of such objects.</p></li>
  </ol>
  
  <p>Is there any better, more elegant solution for this problem?</p>