Search code examples
c++functionwrapperfunctional-programmingtr1

C++: Function wrapper that behaves just like the function itself


How can I write a wrapper that can wrap any function and can be called just like the function itself?

The reason I need this: I want a Timer object that can wrap a function and behave just like the function itself, plus it logs the accumulated time of all its calls.

The scenario would look like this:

// 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();

How can I write this Timer class?

I am trying something like this:

#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();
}

(BTW, I know of gprof and other tools for profiling runtime, but having such a Timer object to log the runtime of a few selected functions is more convenient for my purposes.)


Solution

  • Here is an easy way to wrap functions.

    template<typename T>
    class Functor {
      T f;
    public:
      Functor(T t){
          f = t;
      }
      T& operator()(){
        return f;
      }
    };
    
    
    int add(int a, int b)
    {
      return a+b;
    }
    
    void testing()
    {
      Functor<int (*)(int, int)> f(add);
      cout << f()(2,3);
    }