【发布时间】:2010-10-27 03:16:29
【问题描述】:
如何编写一个可以包装任何函数并且可以像函数本身一样被调用的包装器?
我需要这个的原因:我想要一个 Timer 对象,它可以包装一个函数并像函数本身一样运行,而且它记录所有调用的累积时间。
场景如下所示:
// a function whose runtime should be logged
double foo(int x) {
// do something that takes some time ...
}
Timer timed_foo(&foo); // timed_foo is a wrapping fct obj
double a = timed_foo(3);
double b = timed_foo(2);
double c = timed_foo(5);
std::cout << "Elapsed: " << timed_foo.GetElapsedTime();
我该如何编写这个Timer 类?
我正在尝试这样的事情:
#include <tr1/functional>
using std::tr1::function;
template<class Function>
class Timer {
public:
Timer(Function& fct)
: fct_(fct) {}
??? operator()(???){
// call the fct_,
// measure runtime and add to elapsed_time_
}
long GetElapsedTime() { return elapsed_time_; }
private:
Function& fct_;
long elapsed_time_;
};
int main(int argc, char** argv){
typedef function<double(int)> MyFct;
MyFct fct = &foo;
Timer<MyFct> timed_foo(fct);
double a = timed_foo(3);
double b = timed_foo(2);
double c = timed_foo(5);
std::cout << "Elapsed: " << timed_foo.GetElapsedTime();
}
(顺便说一句,我知道gprof 和其他用于分析运行时的工具,但是拥有这样一个Timer 对象来记录一些选定函数的运行时对我来说更方便。)
【问题讨论】:
-
必须是 C++ 吗?如果你不介意“弄脏你的手”,你可以使用 C 的 varargs 破解一些东西......
标签: c++ function wrapper functional-programming tr1