title: Design Pattern for caching different derived types without using RTTI
body: <p>Let's say I have a family of classes which all implement the same interface, perhaps for scheduling:</p>
  
  <pre><code>class Foo : public IScheduler {
  public:
      Foo (Descriptor d) : IScheduler (d) {}
      /* methods */
  };
  
  class Bar : public IScheduler {
  public:
      Bar (Descriptor d) : IScheduler (d) {}
      /* methods */
  };
  </code></pre>
  
  <p>Now let's say I have a Scheduler class, which you can ask for an IScheduler-derived class to be started for a given descriptor.   If it already exists, you'll be given a reference to it.  If one doesn't exist, then it creates a new one.</p>
  
  <p>One hypothetical invocation would be something like:</p>
  
  <pre><code>Foo &amp; foo = scheduler-&gt;findOrCreate&lt;Foo&gt;(descriptor);
  </code></pre>
  
  <p>Implementing that would require a map whose keys were (descriptor, RTTI) mapped to base class pointers.  Then you'd have to <code>dynamic_cast</code>.  Something along these lines, I guess:</p>
  
  <pre><code>template&lt;class ItemType&gt;
  ItemType &amp; Scheduler::findOrCreate(Descriptor d)
  {
      auto it = _map.find(SchedulerKey (d, typeid(ItemType)));
      if (it == _map.end()) {
          ItemType * newItem = new ItemType (d);
          _map[SchedulerKey (d, typeid(ItemType))] = newItem;
          return *newItem;
      }
      ItemType * existingItem = dynamic_cast&lt;ItemType&gt;(it-&gt;second);
      assert(existingItem != nullptr);
      return *existingItem;
  }
  </code></pre>
  
  <p>Wondering if anyone has a way to achieve a similar result without leaning on RTTI like this.  Perhaps a way that each scheduled item type could have its own map instance?  A design pattern, or... ?</p>