c++ - 构造许多嵌套的类成员

标签 c++ c++14

我想创建一个基类来处理不同数据库系统的许多SQL语句。

我的基本想法是:

struct BaseSQLStmts {

    BaseSQLStmts(Database db) : db(db) {};

    // nested operator class Cmd.
    struct Cmd {
        Cmd(Database db, const char *sqlStmt)
        : db(db), sqlStmt(sqlStmt), sqlHandle(Database::noHandle)
        {};


        Database::Handle operator() () {
            if (sqlHandle==Database::noHandle) {
                sqlHandle = db->prepareSQL(sqlStmt);
            }

            return sqlHandle;
        }

        Database db;
        const char *sqlStmt;
        Database::Handle sqlHandle;
    };

    // SQL-Statement to construct with database and SQL.
    Cmd theSqlStmt;

    // And many more (>50) members of type Cmd.

private:
    Database db;
};

// later use:
BaseSQLStmts *dbSql = new SQLStmtsClassForDB(db);
// ...
db->execute(dbSql->theSqlStmt());

问题是,如何通过创建派生类来构造具有数据库和SQL语句的BaseSQLStmts::Cmd类型的所有成员(超过50个)。我可以在构造函数中为每个SQL定义一个const char *参数,但这是一个容易出错的参数。用于获取命名SQL语句virtual const char* theSqlStmtSQL() = 0的虚拟成员函数不适用于构造函数(纯虚拟成员)。在派生类中进行构造也不起作用。

有什么好主意如何通过在编译时检查语句的完整性来处理此问题?

最佳答案

Any good idea how to handle this without using a complex data structures



那是自相矛盾的。如果您拥有某种类型的50个以上的值,那么您确实应该考虑将它们放在某个容器中。

您的50个查询肯定可以识别它们。甚至像
enum Queries { CreateFoo, GetBarOfFooByBaz, ..., Queries_Count }

std::vector<Cmd> commands(Queries_Count);

会有所帮助。

关于c++ - 构造许多嵌套的类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60493024/

相关文章:

c++ - 没有 Boost 的现代 C++ 中的 bimap 实现

C++重载函数匹配

c++ - 如何在 C 和 C++ 中定义结构之间的某种继承?

c++覆盖一个已经定义的变量

c++ - 当我从虚拟基派生 D 时,为什么 VS2015 中的 sizeof(D) 增加了 8 个字节?

c++ - 如何用 double 来专门化模板类?

c++ - 黑客等级最小最大总和

c++ - 如何根据给定的字符长度拆分 QString?

c++ - QTableView 如何设置特殊行的背景色?

c++ - 管道中 lambda 的意外生命周期