C++ 如何声明以函数作为参数的函数?
抱歉,这个冗长而混乱的标题!我的问题是:我试图编写一个函数来输出另一个函数所花费的时间。通常我只传入函数及其参数,但在本例中,我尝试计时的函数本身将函数作为参数 举一个具体的例子,我正试图让它起作用:C++ 如何声明以函数作为参数的函数?,c++,time,function-pointers,C++,Time,Function Pointers,抱歉,这个冗长而混乱的标题!我的问题是:我试图编写一个函数来输出另一个函数所花费的时间。通常我只传入函数及其参数,但在本例中,我尝试计时的函数本身将函数作为参数 举一个具体的例子,我正试图让它起作用: void foo(void (*f) (T*)){ ...function stuff... } --------not sure what this should be | void runWithTime(void
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
模板
自动运行时间0(T_func)->decltype(_func())
{
startTimer();
_func();
结束计时器();
}
模板
自动运行时间1(T_func,P1_arg1)->decltype(_func(_arg1))
{
startTimer();
_func(_arg1);
结束计时器();
}
//…等等
您可以使用boost::bind做类似的事情,但如果不可用,上述方法也可以
编辑:添加了返回值,如果您的编译器支持c++11(我相信是VC2010/2012,g++4.7或更高版本),则返回值将起作用。事实上,我最近编写了一些代码,目的几乎完全相同。我想到的是:
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";
}
模板
无效计时器(F、T&T、std::字符串常量和标题){
无符号计数;
时钟启动=时钟();
结果=f(t,'N');
时钟停止=时钟();
std::cout当您调用runWithTime(foo)
时,您正在向它传递一个指向函数的指针,该函数是f
参数,但您没有提供g
,因此您不能调用f(g)
…这意味着什么
要简化您的生活,请使用一些typedef:
// 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
是一个带有签名无效条(T*)
看起来很好,您得到了什么错误?当我调用f(g)时,“g未在此范围内声明”
void(*)(T*)
我想你最好还是把它作为一个模板,尽管这样做毫无意义……无论如何@BenjaminKovach我想你想要的是:runWithTime(void(*f)(void(*)(T*)),void(*g)(T*))
…您必须分别将函数和要传递给该函数的函数传递给该函数,除非g
来自其他地方。