title: C++ templated class implementation of the multiton pattern
body: <p>I implemented the multiton pattern using a templated class in C++.</p>
  
  <pre><code>#ifndef MULTITON_H
  #define MULTITON_H
  
  #include &lt;map&gt;
  
  template &lt;typename Key, typename T&gt; class Multiton
  {
  public:    
      static void destroy()
      {
          for (typename std::map&lt;Key, T*&gt;::iterator it = instances.begin(); it != instances.end(); ++it) {
              delete (*it).second;
          }
      }
  
      static T&amp; getRef(const Key&amp; key)
      {
          typename std::map&lt;Key, T*&gt;::iterator it = instances.find(key);
  
          if (it != instances.end()) {
              return *(T*)(it-&gt;second);
          }
  
          T* instance = new T;
          instances[key] = instance;
          return *instance;
      }
  
      static T* getPtr(const Key&amp; key)
      {
          typename std::map&lt;Key, T*&gt;::iterator it = instances.find(key);
  
          if (it != instances.end()) {
              return (T*)(it-&gt;second);
          }
  
          T* instance = new T;
          instances[key] = instance;
          return instance;
      }
  
  protected:
      Multiton() {}
      virtual ~Multiton() {}
  
  private:
      Multiton(const Multiton&amp;) {}
      Multiton&amp; operator= (const Multiton&amp;) { return *this; }
  
      static std::map&lt;Key, T*&gt; instances;
  };
  
  template &lt;typename Key, typename T&gt; std::map&lt;Key, T*&gt; Multiton&lt;Key, T&gt;::instances;
  
  #endif
  </code></pre>
  
  <p>Usage:</p>
  
  <pre><code>class Foo : public Multiton&lt;std::string, Foo&gt; {};
  Foo&amp; foo1 = Foo::getRef("foobar");
  Foo* foo2 = Foo::getPtr("foobar");
  Foo::destroy();
  </code></pre>
  
  <p>Any suggestions for improvements?</p>