Search code examples
c++qttemplatesconcurrencypointer-to-member

member function call doesn´t work in Qt function "run". How I use my template in "run" correctly?


This is my template

template <class T>
void writeData(QVector<T> &vec, const QString &fp, void(T::*method_ptr)(QFile&) )
{
    QFile f(fp);
    if(!f.open(QIODevice::WriteOnly | QIODevice::Append) )
    {
        qDebug() << "File error" << f.error();
    }
    else
    {
        QThread::currentThread();
        for(T &tw : vec)
        {
            (tw.*method_ptr)(f);
        }
    }
    f.close();
}

And here I would use my template:

//teams is like: QVector<teamType> teams
QFuture<void> fut = run(writeData, teams, filePath, &teamType::writeTeams); // no matching function for call 'run'
                    ~~~                              ~~~~~~~~~~~~~~~~~~~
//So, what´s wrong here?

Because this works fine:

writeData(teams, filePath, &teamType::writeTeams);

And "&teamType::writeTeams" cames from the following:

void teamType::writeTeams(QFile &f)
{
    QTextStream out(&f);
    out.setCodec("UTF-16LE");
    out << teamId << "\t" << offsideTrap << "\t" << withoutBall << "\t" << formationId << "\t"
            << attack << "\t" << teamMentality << "\t" << attackTactic1 << "\t"
            << attackTactic2 << "\t" << defenseTactic1 << "\t" << defenseTactic2 << "\t" << captain << "\t"
            << penaltyTakerId << "\t" << kickTakerId << "\t" << leftCornerkickTakerId << "\t" << rightCornerkickTakerId << "\t"
            << numTransfersIn << endl;
}

It´s a member function in class "teamType"


Solution

  • because writeData is a function template there is no mechanism that run can use to get the correct instantiation of that template for the parameters.

    A real easy fix for this is to just wrap the call in a lambda. That would look like

    QFuture<void> fut = run([=](){ writeData(teams, filePath, &teamType::writeTeams); });
    

    and now that the call to writeData is actually done with the function parameters, template argument deduction will succeed and the code will compile.