Running Unknown Functions
Example 68 takes advantage of the type independence of functors to implement a timer. It starts the clock, runs a function, and reports how long it takes to execute. This timer takes a functor of type RWTFunctor<void()>, so it can handle any function that can be encapsulated by such a functor. Because a return value can be ignored for the purpose of timing, it is possible to specify a functor that can handle functions either with or without a return value. Notice how simple it is to do something with functors that would be too difficult to attempt otherwise. Without functors, you would have to write a timer for every possible combination of function return type and argument types.
The timer doesn’t know anything about the function it is launching. Only the callee software that builds the functor needs to know about the function it encapsulates. In this example, the same routine builds the functors and runs them, but it could just as easily be an entirely separate callee building the functors and passing them to the timer, serving as the caller.
Example 68 – Building a timer with functors
#include <rw/functor/RWTFunctor.h>
#include <rw/timer.h>
#include <iostream>
 
// A test function
void work(void) {
...
};
 
// This function takes a functor and runs it, returning the time
// that it took to execute.
 
double timer( RWTFunctor<void()> functor ) { // 1
RWTimer timer;
timer.start();
functor(); // 2
timer.stop;
return timer.elapsedTime();
}
 
int main() {
...
// Timing the work() function
RWTFunctor<void()> work_functor = work; // 3
double work_time = timer(work_functor); // 4
cout << "work() took " << work_time << " to run" << endl;
 
return 0;}
//1 The timer() function takes a functor of type RWTFunctor<void()> and returns a double.
//2 timer() runs RWTFunctor<void()>’s operator(), which invokes the functor instance and launches its encapsulated function.
//3 Constructs a handle instance, work_functor, for a functor object.
//4 Hands the functor work_functor to the timer() function. When timer() runs work_functor, it launches the encapsulated function, work().