生成对象时宏和模板的组合

Combination of macros and template in generating Object

本文关键字:组合 对象      更新时间:2023-10-16

我创建了一个模板类来填充类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
 }

我收到帮助程序未声明的标识符错误!!如果我不使用函数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
}