如何声明一个以函数为参数的函数
How to declare a function that takes a function with a function as an argument?
不好意思,标题太啰嗦了!这是我的问题:我正试图写一个函数来输出另一个函数所需的时间。通常我只传递函数和它的参数,但在这个例子中,我试图计时的函数自己接受函数作为参数。
对于一个具体的例子,我正在努力使这个工作:
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");
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数