C++-模板函数接受绑定函数作为参数并将其传递给另一个函数
C++ - Template function to accept bound function as parameter and pass it to another function
在回答前面的一个问题(一个在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); }
// ^^^^^^
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如何在C++中将函数发送到另一个进程
- 如何在qt中从另一个类调用函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 将 N-arg 函数包装到另一个函数中
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- C++从另一个函数退出函数
- 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?
- 在一个类中使用另一个类中的函数,而不在 c++ 中使用继承
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?