我创建了一个模板类来填充类 T 的一些对象,但是 T 的对象在网络中是共享的,我不想提供关于它们的信息所以我为每个类 T 和一个宏创建了一个帮助类:
class Entity {
// just Properties
}
class EntityHelper{
// needed method for fill from database
}
#define DBH(x) x##Helper
这是一个用于填充对象列表的上下文类的函数
template<class T>
QList<T> ContextClass::query(const QString& q){
T inst;
DBH(T) helper;
// and another methods
}
我收到 THelper 未声明的标识符错误!!
如果我不使用函数 m->query(q);我没有收到错误消息??
我知道我可以使用另一种方法来做到这一点,但这种方法有什么问题?
更新:
好吧,看来我必须使用我用过的另一种方法?
template <class T>
class Helper {
Helper<T>* createInstance();
//some methods
}
class EntityHelper : public Helper<Entity>
{
EntityHelper* createInstance();
// query needed for entity table database
}
最佳答案
记住宏只是文本替换,所以你的代码变成:
template<class T>
QList<T> ContextClass::query(const QString& q){
T inst;
THelper helper;
// and another methods
}
这是废话...
在您的情况下,只需使用模板:
template<class T>
class Helper;
template<>
class Helper<Entity>
{
// needed method for fill from database
};
template<class T>
QList<T> ContextClass::query(const QString& q){
T inst;
Helper<T> helper;
// and another methods
}
关于c++ - 宏与模板结合生成Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25861321/