Search code examples
c++templatesfactoryfactory-pattern

C++ Factory Pattern With Templates


I'm trying to code an abstract factory using c++ templates. Due to the fact I've never done things like that before I'm encountering troubles. The code I wrote, as you can verify by yourself, is wrong and I have no idea on how to correct it. My idea is that there are two templated classes that will contain the base_class and the derived_class, so this class can be used with any type of class. It is templated the key too for the same reason.

#ifndef _t_factory_h_
#define _t_factory_h_

#include <iostream>
#include <map>

template < class T >
class base_creator
{
  public:
   virtual ~base_creator(){ };
   virtual T* create() = 0;
};


template < class derived_type , class base_type >
class derived_creator : public base_creator<base_type>
{
  public:
  base_type* create()
  {
   return new derived_type;
  }
};

template <class _key, class base >
class factory
{
   public:
     void register_type(_key id , derived_creator<derived_type,base_type>* _fn)
  {
    _function_map[id] = _fn;
  }

  base* create(_key id)
  {
    return _function_map[id]->create();
  }

 ~factory()
 {
   auto it = _function_map.begin();
   for(it ; it != _function_map.end() ; ++it)
   {
     delete (*it).second;
   }
  }

  private:
     std::map<_key , derived_creator<derived_type,base_type>*> _function_map;
   };

#endif /* defined _t_factory_h_ */

If somenone can help me to correct this code I would be grateful.


Solution

  • Problem solved. Here is the code:

    #ifndef _t_factory_h_
    #define _t_factory_h_
    
    #include <iostream>
    #include <map>
    
    template < class T >
    class base_creator
    { 
      public:
      virtual ~base_creator(){ };
      virtual T* create() = 0;
    };
    
    
    template < class derived_type , class base_type >
    class derived_creator : public base_creator<base_type>  
    {
     public:
     base_type* create()
     {
      return new derived_type;
     }
    };
    
    template <class _key, class base_type >
    class factory
    {
     public:
       void register_type(_key id , base_creator<base_type>* _fn)
       {
         _function_map[id] = _fn;
       }
    
       base_type* create(_key id)
       {
          return _function_map[id]->create();
       }
    
      ~factory()
      {
        auto it = _function_map.begin();
        for(it ; it != _function_map.end() ; ++it)
        {
          delete (*it).second;
        }
    }
    
     private:
       std::map<_key , base_creator<base_type>*> _function_map;
    };
    
    #endif /* defined _t_factory_h_ */