模板化静态Create函数

Templating static Create function

本文关键字:Create 函数 静态      更新时间:2023-10-16

我有以下基类:

class Base abstract
{
public:
   virtual ~Base() {};
protected:
   Base() {};
   virtual bool Initialize() abstract;
};

在扩展非抽象类时,我总是定义静态的Create函数。

class Next : public Base
{
public:
   static Next* Create(/*eventual params*/);
   ~Next() {};
protected:
   Next(/*eventual params*/) {};
   virtual bool Initialize() {/*...*/};
};

创建函数看起来总是这样:

Next* Next::Create(/*eventual params*/)
{
   bool succes;
   Next* next = new Next(/*eventual params - same as above*/);
   succes = next->Initialize();
   if(!succes)
   {
      return NULL;
   }
   return next;
}

我的问题是;有可能缩短这个功能吗?例如,使用模板还是将其封闭在一行中?

只需在函数中使用模板创建一个泛型类并调用其中的某个函数很简单,问题在于/*eventual params*/部分。您可以使用名为的参数包(也称为可变模板)来解决此问题。

也许是这样的:

template<typename T, typename ...A>
T* create(A... args)
{
    T* object = new T(std::forward<A>(args)...);
    if (object->Initialize())
        return object;
    delete object;
    return nullptr;
}

对于您的示例类Next可以像一样使用

Base* pointer_to_next = create<Next>(/* eventual arguments */);

当然,它需要C++11。