dimanche 1 décembre 2019

In C++, is it possible to define a function with a varying code block to be executed and passed via another function?

I have a class handling SQL queries (it uses Qt functions, but I think this doesn't matter). All queries that write data have the exact same base frame that looks like this:

bool Database::someSqlFunction(some variables)
{
    if (! startTransaction()) {
        return false;
    }

    QSqlQuery query(m_db);

    try {
        ... Code using the passed variables and query ...
        commitTransaction();
    } catch (...) {
        rollbackTransaction(query);
        return false;
    }

    return true;
}

Is it possible to re-use this code so that it won't have to be defined per function? I thought about using a function to be called with a pointer to the function containing the varying code, but the signature is different for each function and I thus would have to define an overloaded one for each case; I also thought about using the preprocessor to generate the function, but it's the same problem with the different number and type of arguments.

Can a block of code to be executed be passed to another function? Or can this be done via a function template?

Aucun commentaire:

Enregistrer un commentaire