Ben*_*ach 3 c++ time function-pointers
对不起,这个冗长且令人困惑的标题!这是我的问题:我正在尝试编写一个函数来输出另一个函数所需的时间.通常我只是传递函数及其参数,但在这个例子中,我试图计时的函数将函数作为参数.
举一个具体的例子,我试图让它工作:
void foo(void (*f) (T*)){
...function stuff...
}
--------not sure what this should be
|
void runWithTime(void (*f) (void (*g) (T*))){
f(g)
}
//runWithTime(foo);
Run Code Online (Sandbox Code Playgroud)
我希望能够打电话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
Run Code Online (Sandbox Code Playgroud)
你可以用boost :: bind做类似的事情,但是如果没有,那么上面应该可以做到.
编辑:添加返回值,如果您的编译器支持c ++ 11(VC2010/2012,g ++ 4.7或更高版本我相信),它将起作用