我如何为此编写一个好的模板。我收到此错误:“成员引用基本类型'void'不是结构或联合”

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

这是我尝试创建的模板的代码。非常感谢您的一些建议和技巧。这是对的还是您可以创造更好的?实际上,我收到以下消息:“成员引用基类型'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;
...

这是对的吗?

c++ qt templates methods referenceerror
2个回答
0
投票

您正在传递指向成员函数的指针(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));
}

0
投票

我认为这行不通。我们必须考虑,我将通过一个成员!功能到功能。通过以下方式在模板中使用此成员函数:

for(T &tw : vec)
{
    tw.func(f); // I think this is correct
  //func(f).tw;     // not this                  
}

这意味着(我不确定)在std::function<void(int)> func中,我们必须建议始终在此模板中包含一个类。

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