首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >作为参数的函数调用的C++传递列表

作为参数的函数调用的C++传递列表
EN

Stack Overflow用户
提问于 2020-08-25 15:49:20
回答 2查看 93关注 0票数 1

我目前正在设置一个单元测试助手类,它在Qt中使用C++11验证信号是否在测试期间发出,与其顺序无关,例如:

代码语言:javascript
复制
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());
}

我有十几个这样的函数,都是用来检查是否发出了某些信号。现在我需要编写顺序很重要的测试。在这些测试中,我需要进行验证,例如:

代码语言:javascript
复制
Volume set to 10
Volume set to 50

但完全是按照这个顺序。现在我的问题是,是否有一种方法可以使用可变模板或类似的方法来将函数调用列表传递给函数。我将通用的顺序检查函数想象为如下所示:

代码语言:javascript
复制
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
    }
}

有什么好的方法可以做到这一点,这样我就不必为每个函数创建顺序敏感的测试函数了吗?

EN

回答 2

Stack Overflow用户

发布于 2020-08-25 16:00:33

另一种选择是使用lambdas。下面是如何实现的:

for

  • 定义方法取std::functions

  • inside的列表,向量该方法做一个循环,并调用每个函数
  1. 来调用该方法传递一个填充了λ的向量进行调用...

代码语言:javascript
复制
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);
票数 1
EN

Stack Overflow用户

发布于 2020-08-25 15:59:19

可以使用std::vectorstd::function将具有相同签名的函数列表传递给checkExecutionOrder

代码语言:javascript
复制
#include <vector>
#include <functional>

using FunctionCall = std::function< void(int,int) >;
using FunctionCallList = std::vector<FunctionCall>;

void checkExecutionOrder(FunctionCallList call_list){

    for (auto f : call_list) {    
         f(42,42);
    }
}

void foo(int x,int y){}

int main() {
    checkExecutionOrder( { foo,foo } );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63574285

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档