【问题标题】:C++ - Template function to accept bound function as parameter and pass it to another functionC++ - 模板函数接受绑定函数作为参数并将其传递给另一个函数
【发布时间】:2014-01-12 23:56:48
【问题描述】:

在回答上一个问题 (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 的问题,而不是传递的函数调用。任何有关如何使用传递的函数调用生成工作的提示将不胜感激。

【问题讨论】:

  • 您遇到了什么错误?
  • 在 /usr/include/c++/4.7/algorithm:63:0 包含的文件中,来自 main.cpp:2: /usr/include/c++/4.7/bits/stl_algo.h: 在'void std::generate(_FIter, _FIter, _Generator) 的实例化 [with _FIter = __gnu_cxx::__normal_iterator >; _Generator = repeatFunction(F) [with F = std::_Bind))(std::vector)>]::]': 函数.h:50:4: 来自 'std::vector repeatFunction(F) [with F = std::_Bind))(std::vector)>]'
  • main.cpp:29:72: 从这里需要 /usr/include/c++/4.7/bits/stl_algo.h:5083:2: 错误: void 值没有被忽略,因为它应该是

标签: c++ templates c++11


【解决方案1】:

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

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

【讨论】:

  • 哇,我想我一直盯着这种方式太久了。再次感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-14
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多