在对象工厂中注册对象创建器 [英] Register an object creator in object factory

查看:203
本文介绍了在对象工厂中注册对象创建器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有方便的对象工厂模板,通过它们的类型id名称创建对象。实现很明显: ObjectFactory 包含从 std :: string 到对象创建器函数的映射。

I have the convenient object factory template that creates objects by their type id names. The implementation is pretty obvious: ObjectFactory contains the map from std::string to object creator function. Then all objects to be created shall be registered in this factory.

我使用以下宏:

#define REGISTER_CLASS(className, interfaceName) \
   class className; \
   static RegisterClass<className, interfaceName> regInFactory##className; \
   class className : public interfaceName

其中 RegisterClass

where RegisterClass is

   template<class T, class I>
   struct RegisterClass
   {
      RegisterClass()
      {
         ObjectFactory<I>::GetInstance().Register<T>();
      }
   };

使用

class IFoo
{
public:
   virtual Do() = 0;
   virtual ~IFoo() {}
}

REGISTER_CLASS(Foo, IFoo)
{
   virtual Do() { /* do something */ }
}

REGISTER_CLASS(Bar, IFoo)
{
   virtual Do() { /* do something else */ }
}

类别在工厂中同时定义和注册。

Classes are defined and registered in factory simultaneously.

问题是<。code> regInFactory ... 静态对象在.h文件中定义,因此它们将被添加到每个翻译单元。相同的对象创建者将被注册多次,更重要的是,将有大量的具有静态存储持续时间的冗余对象。

The problem is that regInFactory... static objects are defined in .h files, so they will be added to every translation unit. The same object creator will be registered several times, and, more important, there will be a lot of redundant objects with static storage duration.

有任何方法优雅的注册(不复制/粘贴类和接口名称),但是不要在全球范围内传播多余的静态对象?

Is there any way to do such elegant registration (not to copy/paste class and interface names), but do not spread redundant static objects around the globe?

如果一个好的解决方案需要一些VC ++特定的扩展

If a good solution needs some VC++ specific extensions (not conforming to C++ standard), I will be OK with that.

推荐答案

所以你想把变量定义放在头文件中吗?有一种可移植的方式:模板类的静态变量。所以我们得到:

So you want to put variables definitions in header file? There is a portable way: static variables of template classes. So we get:

template <typename T, typename I>
struct AutoRegister: public I
{
    // a constructor which use ourRegisterer so that it is instantiated; 
    // problem catched by bocco
    AutoRegister() { &ourRegisterer; } 
private:
    static RegisterClass<T, I> ourRegisterer;
};

template <typename T, typename I>
RegisterClass<T, I> AutoRegister<T, I>::ourRegisterer;

class Foo: AutoRegister<Foo, IFoo>
{
public:
    virtual void Do();         
};

请注意,我保留了IFoo的继承非虚拟。如果有多次从该类继承的风险,它应该是虚拟的。

Note that I've kept the inheritance of IFoo non virtual. If there is any risk of inheriting from that class multiple times, it should be virtual.

这篇关于在对象工厂中注册对象创建器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆