我有一个非常简单的C++查找表调度命令:子类查找表
template <class T> Action* CreateAction(Command *c)
{
return new T(c);
}
typedef Action* CreateActionFunc(Command *c);
typedef struct ActionTable {
string name;
CreateActionFunc *func;
} ActionTableEntry;
vector<ActionTableEntry> GlobalActionTable = {
{ "quit" , &CreateAction<DoQuit> },
};
这工作得很好,但我宁愿让我的CreateAction功能构建堆栈中的新对象,并通过值返回。但是当我写这个:
template <class T> T CreateAction(Command *c)
{
return T(c);
}
typedef Action CreateActionFunc(Command *c);
然后程序将不再编译。首先,我得到一个错误,即一个抽象类无法实例化(在typedef行上),并且还有一个错误,即该表的初始化列表与该向量的类型不匹配。
有一个非常类似的问题here但每个答案在工厂方法中使用new
,这是明确我想要避免的。如何才能做到这一点?
感谢Kiroxas,我想这回答了这个问题! – Segfault