Pages

2012-06-01

Local class awesomeoness

Context: There are these bunch of classes that implements an interface iA. The user of these classes needs to instantiate an object every time they want to use it. However, we dont want to teach the the user about how to instantiate an object. So, we decided to give the user a Factory object which implements an interface iF to create an object providing iA. This seemed super awesome until we figured that we would require more than a dozen Factory classes which vary only in the types and number of parameters sent to . So, hopped on to meta-programming and carved out a couple of templates. The pain still did not end. We still had to instantiate these templates, wrap them in a boost::shared_ptr and give them to the user. Attempts on templatising that turned out to be ugly and not so cool.

Eventually, "local classes" came to the rescue. So, here is a factory of factories :P

template 
RPCHandlerFactory *
_create_rpc_handler_factory (hlog::Logger::ptr_type logger, P1 p1_)
{
  class Factory : public RPCHandlerFactory
  {
  public:
    Factory (hlog::Logger::ptr_type logger, P1 p1)
      : m_Logger (logger),
        m_p1 (p1) { }

    RPCHandler::ptr_type operator() (RPCServer *server, rpcRequest_Ptr req)
    {
      RPCHandler::ptr_type ph (new T (m_Logger, server, req, m_p1));
      ph->set_this_ptr (ph);
      return ph;
    }

  private:
    hlog::Logger::ptr_type m_Logger;
    P1 m_p1;
  };

  return new Factory (logger, p1_);
}

template 
RPCHandlerFactory::ptr_type
create_rpc_handler_factory (hlog::Logger::ptr_type logger, P1 p1_)
{
  RPCHandlerFactory * pfactory = _create_rpc_handler_factory
    (logger, p1_);
  RPCHandlerFactory::ptr_type factory (pfactory);
  return factory;
}


And, creating a factory is like:

RPCHandlerFactory::ptr_type factory =
      create_rpc_handler_factory < rpcAHandler > (m_Logger, m_machine);


Now, we could have combined both the functions together. But there is this C++03 quirk which goes away with C++11.

Update-1:

The issue that wont allow combining the functions: http://stackoverflow.com/questions/742607/using-local-classes-with-stl-algorithms

Update-2:

Blogger ate the angle brackets in the instantiation. Fixed it. :)

2 comments:

Neers said...

Damn!! Gimme good old C n Data Structures!!

Joe Steeve said...

C is that old high-school sweetheart who brings tears of joy every time you think of her.