成员函数调用在Qt函数“运行”中不起作用。如何在“运行”中正确使用模板?

问题描述 投票:0回答:2

这是我的模板

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();
}

这里我将使用我的模板:

//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?

因为这样可以正常工作:

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

和“&teamType :: writeTeams”来自以下位置:

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;
}

这是“ teamType”类中的成员函数

c++ qt templates concurrency member-function-pointers
2个回答
0
投票

我有解决方案,现在一切正常:

template <class T>
void writeTeamsForLoop(QVector<T> &vec, const QString fp, void(T::*method_ptr)(QFile&) ) 
{                                       //QString must not be a reference(const QString fp)!
    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();
}

Lambda代码:

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

0
投票

因为writeData是功能模板,所以没有任何机制可以使run用于为参数获取该模板的正确实例化。

真正简单的解决方法是将调用包装在lambda中。看起来像

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

并且现在对writeData的调用实际上是通过函数参数完成的,模板参数推导将成功,并且代码将被编译。

© www.soinside.com 2019 - 2024. All rights reserved.