如何声明一个以函数为参数的函数

How to declare a function that takes a function with a function as an argument?

本文关键字:函数 参数 一个以 何声明 声明      更新时间:2023-10-16

不好意思,标题太啰嗦了!这是我的问题:我正试图写一个函数来输出另一个函数所需的时间。通常我只传递函数和它的参数,但在这个例子中,我试图计时的函数自己接受函数作为参数。

对于一个具体的例子,我正在努力使这个工作:

void foo(void (*f) (T*)){
  ...function stuff...
}
                  --------not sure what this should be
                 | 
void runWithTime(void (*f) (void (*g) (T*))){
  f(g)
}
//runWithTime(foo);

我希望能够调用runWithTime(foo),但我不确定runWithTime的参数应该是什么类型。

任何帮助将是伟大的!

一个简单的解决方案:

template<typename T>
auto runWithTime0(T _func) -> decltype(_func())
{
  startTimer();
  _func();
  endTimer();
}
template<typename T, typename P1>
auto runWithTime1(T _func, P1 _arg1) -> decltype(_func(_arg1))
{
  startTimer();
  _func(_arg1);
  endTimer();
}
// ...etc

你也可以用boost::bind做一些类似的事情,但是如果不能用,上面的方法就可以了。

编辑:添加返回值,这将工作,如果你的编译器支持c++11 (VC2010/2012, g++4.7或更高的我相信)

当你调用runWithTime(foo)时,你传递给它一个指向函数的指针,这是f参数,但你不提供g,所以你不能调用f(g)…这是什么意思?

为了使你的生活更简单,使用一些类型定义:

// A pointer to a function that takes a single T* argument
typedef void (*func_ptr)(T*);
void foo(func_ptr f){
  ...function stuff...
}
// A pointer to a function that takes a single func_ptr argument
typedef void (*funcfunc_ptr)(func_ptr);
void runWithTime(funcfunc_ptr f, func_ptr g){
  f(g)
}

现在很明显,你需要传递两个参数给runWithTime,例如runWithTime(foo, NULL)runWithTime(foo, bar),其中bar是一个签名为void bar(T*)的函数

碰巧,我最近写了一些几乎完全相同目的的代码。我想到的是:

template <class F, class T>
void timer(F f, T &t, std::string const &title) { 
    unsigned count;
    clock_t start = clock();
    result = f(t, 'N');
    clock_t stop = clock();
    std::cout << std::left << std::setw(30) << title << "tResult: " << result;
    std::cout << "tTime: " << double(stop-start)/CLOCKS_PER_SEC << "n";
}

用法如下:timer(function1, infile, "Running function 1");