c++ - C++将函数调用列表作为参数传递

标签 c++ function qt templates variadic-templates

我目前正在建立一个单元测试帮助程序类,该类在Qt中使用C++ 11进行验证,以验证在与命令顺序无关的测试过程中是否发出了信号,例如:

void TestUtils::verifyVolumeAdjustment(const QSignalSpy &vol_spy, uint percent)
{
    for(QList<QVariant> vol_call_args : vol_spy){
        if(vol_call_args.at(0).toInt() == percent)
        {
            return;
        }
    }
    QString err = QString("volume never set to %1").arg(QString::number(percent));
    QFAIL(err.toLocal8Bit().constData());
}
我有很多这样的功能,用于检查是否发出了某些信号。现在,我需要在顺序很重要的地方编写测试。在这些测试中,我需要验证例如:
Volume set to 10
Volume set to 50
但是完全按照这个顺序。现在我的问题是,是否可以使用可变参数模板或类似的方法来将函数调用列表传递给函数。我想象通用顺序检查功能是这样的:
void checkExecutionOrder(const QSignalSpy& spy, FunctionCallList call_list){
    
    for(int i = 0; i < call_list.length(), i++){
         QSignalSpy temp;
         temp.append(spy.at(i)); //create a temporary copy of that caught signal to ensure its the only thing validated
         call_list[i].call(temp, arguments); // call the function from the list with modified spy and remaining arguments
    }
}
有什么好的方法可以做到这一点,所以我不必为每个函数创建一个顺序敏感的测试函数吗?

最佳答案

另一个选择是使用lambda。
方法如下:

  • 定义获取列表的方法,std::functions的 vector
  • 方法内的
  • 进行for循环并调用每个函数
  • 调用方法传递一个填充有lambda的 vector ,称为...
  • void myFooFunction(QVector<std::function<int(int)>>& myVec)
    {
        for(auto& x:myVec)
        {
            x(1);
        }
    }
    
    int main(int argc, char* argv[])
    {
    
        QVector<std::function<int(int)>> x;
        auto f1 = [](int x){qDebug() << "x ++" << x; return x++;};
        auto f2 = [](int x){qDebug() << "x --" << x; return x--;};
        x.push_back(f1);
        x.push_back(f2);
        myFooFunction(x);
    

    关于c++ - C++将函数调用列表作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63574285/

    相关文章:

    c++ - 在 C++ 中循环访问 2D tic-tac-toe 数组的好方法?

    c++ - 类不存在默认构造函数但未默认传递

    javascript - 从函数参数访问对象

    c++ - 在 QGraphicsItem 之上使用 QRubberBand

    QT:使用缩放调整 QImage 的大小

    c++ - 有没有办法在 C++ 中使用类型文字?

    c++ - 警告 : non-constant array size in new, 无法验证初始化列表的长度

    java - 为什么我的哈希函数收到负值?

    python - 如何在函数内执行Python函数而不停止执行

    c++ - Qt/C++ 将指针指向另一个构造函数