Re: Problem implementing an object factory
 
Stephen Torri wrote:
Here is my attempt at implementing a object factory. The purpose of this
is to replace a large switch statement in a factory class with the
functors. I get an error at line 88, marked, "expected primary-expression
before ')' token". I am using Modern C++ Design chapter 8 as a guide.
Stephen
---------------------
#include <map>
#include <iostream>
namespace tool
{
  namespace component
  {
    class Component;
  }
  namespace infrastructure
  {
    class Component_Factory
    {
    public:
      typedef component::Component* (*CreateComponentCallback)();
      
      bool RegisterComponent ( int component_id,
                   CreateComponentCallback call_func )
      {
    return m_callbacks.insert ( CallbackMap::value_type ( component_id,
    call_func ) ).second;
      }
      
      bool UnregisterComponent ( int component_id ) {
    return m_callbacks.erase ( component_id ) == 1;
      }
      component::Component* CreateComponent ( int component_id ) {
    CallbackMap::const_iterator pos = m_callbacks.find ( component_id );
    if ( pos == m_callbacks.end() )
      {
        std::cerr << "Unknown Component ID" << std::endl; abort();
      }
    return (pos->second)();
      }
      
    private:
      typedef std::map<int, CreateComponentCallback> CallbackMap;
      
      CallbackMap m_callbacks;
    };
  }
  namespace component
  {
    class Component
    {};
    class Apple : public Component
    {
    public:
      static const int ID = 1;
      Component* operator()()
      {
    return new Apple;
      }
    };
    class Blueberry : public Component
    {
    public:
      static const int ID = 5;
      Component* operator()()
      {
    return new Blueberry;
      }
    };
  }
}
int main (int, char**)
{
  tool::infrastructure::Component_Factory fact_ref;
  /* LINE 88 */
  fact_ref.RegisterComponent ( tool::component::Apple::ID,
  tool::component::Apple );
the second param of Registercomponent is typeof
typedef component::Component* (*CreateComponentCallback)();
which is a free function.
now you trying to assign it with a class type, which is never valid 
anywhere to use type as a function actual parameter.
so a quick and simple change is
 >     class Apple : public Component
 >     {
 >     public:
 >
 >       static const int ID = 1;
 >
 >       Component* operator()()
         static Component* Create() // factory method
 >       {
 > 	return new Apple;
 >       }
 >     };
 >   fact_ref.RegisterComponent ( tool::component::Apple::ID,
 >   tool::component::Apple );
fact_ref.RegisterComponent ( tool::component::Apple::ID,
     &tool::component::Apple::Create );
  fact_ref.UnregisterComponent ( tool::component::Apple::ID );
  return 0;
}
-- 
Thanks
Barry