C++-模板函数接受绑定函数作为参数并将其传递给另一个函数

C++ - Template function to accept bound function as parameter and pass it to another function

本文关键字:函数 另一个 参数 绑定 C++-      更新时间:2023-10-16

在回答前面的一个问题(一个在C++中执行任何类型和数量的参数的函数的函数)时,我发现当将一个函数作为另一个函数的参数传递时,我可以使用std::bind方法来绑定参数。然后如何将其传递给另一个函数?中间功能(repeatFunction)和计时器的代码如下所示:

template<typename F>
double timer(F function) {
clock_t tstart, tend;
tstart = clock();
function();
tend = clock();
return ((double)tend - tstart) / CLOCKS_PER_SEC;
}
template<typename F>
std::vector<double> repeatFunction(F function) {
std::vector<clock_t> numCalls(9);
std::vector<double> info;
std::generate(numCalls.begin(), numCalls.end(), [&](){ timer(function); });
info.push_back(mean(numCalls));
info.push_back(standardDeviation(numCalls));
return info;
}

代码获取一个传递的函数并运行它多次,然后返回函数运行所花费的时间。函数(F函数)从main绑定,如下所示:

#include <cstdlib>
#include <algorithm>
#include <numeric>
#include <vector>
#include <cmath>
#include <ctime>
#include <iostream>
#include "functions.h"
int main(void) {
std::vector<double> x;
x.push_back(53.0);
x.push_back(61.0);
x.push_back(49.0);
x.push_back(67.0);
x.push_back(55.0);
x.push_back(63.0);
std::vector<double> info = repeatFunction(std::bind(mean<double>, x));
return 0;
}

我是否需要以某种方式获取参数,然后在repeatFunction函数中重新绑定它们?

EDIT:这实际上似乎是std::generate的问题,而不是实际传递的函数调用。任何关于如何使用传递的函数调用使generate工作的提示都将不胜感激。

std::generate接收的谓词需要返回一个值:

[&] { return timer(function); }
//    ^^^^^^