在回答上一个问题(A function to execute any function with any types and numbers of parameter in 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函数中将其重新绑定?
编辑:实际上似乎是std :: generate的问题,实际上不是传递的函数调用。任何有关如何使生成的函数与传递的函数调用配合使用的技巧,将不胜感激。
最佳答案
std::generate
收到的谓词需要返回一个值:
[&] { return timer(function); }
// ^^^^^^
关于c++ - C++-模板函数接受绑定(bind)函数作为参数并将其传递给另一个函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21070731/