模板化静态Create函数
Templating static Create function
我有以下基类:
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。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- QThread::create 似乎没有将参数传递给函数
- 使用宏替换工厂模式样式 API 中的"create()"函数
- 如果它被定义为 C++ 类中的成员函数,我得到了"non-standard syntax; use '&' to create a pointer to member"
- 为什么 QSharedPointer:<T>:create 不完整对象的调用析构函数?
- 模板化静态Create函数
- 埃菲尔"create" C++构造函数?
- c++ clone和create作为虚拟构造函数
- 在c++中实现Interface类的create函数