这是我尝试创建的模板的代码。非常感谢您的一些建议和技巧。这是对的还是您可以创造更好的?实际上,我收到以下消息:“成员引用基类型'void'不是结构或联合”
template <class T>
void example(QVector<T> &vec, const QString &fp, std::function<void(QFile&)> func)
{ /* Is this right? I don´t have to say "T" anywhere?
Because here I would pass a method from a class(void myClass::method(QFile&) )*/
QFile f(fp);
if(!f.open(QIODevice::WriteOnly | QIODevice::Append) )
{
qDebug() << "File error" << f.error();
}
else
{
QThread::currentThread();
for(T &tw : vec)
{
//tw.func(f);
func(f).tw; // member reference base type 'void' is not a structure or union
}
}
f.close();
}
功能可能是这样:
//...class definition...
//declaration of the method:
void writeTeams(QFile&);
//definition (this pass to func)
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;
}
我将在以下代码中使用模板:
...
filePath = "teamwrite.csv";
QFuture<void> f = run(example, teams, filePath, &teamType::writeTeams); //teams came from this: QVector<teamType> teams;
...
这是对的吗?
您正在传递指向成员函数的指针(pmr),其中您需要指向函数的指针(std::function
的转换构造函数。
您需要将writeTeams
声明为static
,否则将pmr bind声明为teamType
的实例(pmr的不可见的第一个参数),以给出一个std::function
单个参数。
让我们将您的代码简化为一个最小的完整示例(因为Qt和模板的内容在这里只是分散注意力:]
#include <functional>
void example(std::function<void(int)> func)
{
func(1);
}
struct teamType
{
void writeTeams(int);
};
int main()
{
example(&teamType::writeTeams);
}
无法编译:
60725415.cpp: In function ‘int main()’:
60725415.cpp:19:13: error: could not convert ‘&teamType::writeTeams’ from ‘void (teamType::*)(int)’ to ‘std::function<void(int)>’
19 | example(&teamType::writeTeams);
| ^~~~~~~~~~~~~~~~~~~~~
| |
| void (teamType::*)(int)
我可以写(如果writeTeams
不需要任何teamType
成员):
struct teamType
{
static void writeTeams(int);
};
或者我可以绑定到teamType
的特定实例:
int main()
{
using namespace std::placeholders;
teamType the_team;
example(std::bind(&teamType::writeTeams, the_team, _1));
}
我认为这行不通。我们必须考虑,我将通过一个成员!功能到功能。通过以下方式在模板中使用此成员函数:
for(T &tw : vec)
{
tw.func(f); // I think this is correct
//func(f).tw; // not this
}
这意味着(我不确定)在std::function<void(int)> func
中,我们必须建议始终在此模板中包含一个类。