dimanche 4 juin 2023

How to set expected template argument base type

I have an interface base class:

template <typename T>
class BaseDicModel {
public:
  virtual ~BaseDicModel() {}
  virtual QString text() const    = 0;
  virtual int id() const          = 0;
  virtual void parseQuery(QSqlQuery *q) = 0;
  virtual QJsonObject toJson()    = 0;
};

and a template function, which is supposed to execute sql query and return dictionary depending on template class.

 template <class T>
  /**
   * @brief Loading dictionary from database
   * @param sqlQuery sql query to execute
   * @return Dictionary of type T
   * !!! T MUST BE DERIVED FROM BaseDicModel !!!
   */
  static QList<T *>
  getDictionary(QString sqlQuery) {
    QList<T *> result;
    QString conName = "regionConnection";
    {
      QSqlDatabase conn = getConnectionV2(
          conName, ConfigService::getInstance()->get_db_connection());
      //        int ret = -1;
      bool bOpen = false;
      if (!conn.isOpen()) {
        if (!conn.open()) {
          qWarning() << "Error while open db";
          return result;
        }
        bOpen = true;
      }

      QSqlQuery *query = new QSqlQuery(conn);

      query->prepare(sqlQuery);
      if (query->exec()) {
        while (query->next()) {
          T *row = new T();
          row->parseQuery(query);
          result.append(row);
        }
      } else {
        qWarning() << "Error while exec query:" << query->lastError().text();
      }
      delete query;
      if (bOpen) { conn.close(); }
    }
    QSqlDatabase::removeDatabase(conName);
    return result;
  }
};

it works fine, but i have a problem: template class can be ANY class right now,and what i'd like to get is template only for BaseDicModel derived classes. Something like this pseudocode:

template<class T implements BaseDicModel>

Can you please give me any hints on how to make it work? Question must be silly, but i don't seem to get it. Thanks.

Aucun commentaire:

Enregistrer un commentaire