Register an object creator in object factory

前端 未结 4 536
南方客
南方客 2020-12-06 04:02

I have the convenient object factory template that creates objects by their type id names. The implementation is pretty obvious: ObjectFactory contains the map

4条回答
  •  难免孤独
    2020-12-06 04:15

    Cygon's answer is probably what you need, but you also might get away with lazy registration, depending what exacly is registration for.

    Move registration into special base class and attach that besides interface in the macro.

    Inside constructor use a local static flag, so that each class registers only once on first instanse creation.

    Probably won't compile, but you should get what I meant:

    template
    class RegistratorBase
    {
    public:
         RegistratorBase()
         {
              static bool registered = false;
              if(!registered)
                    ObjectFactory::GetInstance().Register();
         }
    };
    
    #define REGISTER_CLASS(className, interfaceName) \
      class className : public interfaceName, private RegistratorBase
    

提交回复
热议问题