Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: Function wrapper that behaves just like the function itself
    text
    copied!<p>How can I write a wrapper that can wrap any function and can be called just like the function itself? </p> <p>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.</p> <p>The scenario would look like this:</p> <pre><code>// a function whose runtime should be logged double foo(int x) { // do something that takes some time ... } Timer timed_foo(&amp;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 &lt;&lt; "Elapsed: " &lt;&lt; timed_foo.GetElapsedTime(); </code></pre> <p>How can I write this <code>Timer</code> class?</p> <p>I am trying something like this:</p> <pre><code>#include &lt;tr1/functional&gt; using std::tr1::function; template&lt;class Function&gt; class Timer { public: Timer(Function&amp; fct) : fct_(fct) {} ??? operator()(???){ // call the fct_, // measure runtime and add to elapsed_time_ } long GetElapsedTime() { return elapsed_time_; } private: Function&amp; fct_; long elapsed_time_; }; int main(int argc, char** argv){ typedef function&lt;double(int)&gt; MyFct; MyFct fct = &amp;foo; Timer&lt;MyFct&gt; timed_foo(fct); double a = timed_foo(3); double b = timed_foo(2); double c = timed_foo(5); std::cout &lt;&lt; "Elapsed: " &lt;&lt; timed_foo.GetElapsedTime(); } </code></pre> <p>(BTW, I know of <code>gprof</code> and other tools for profiling runtime, but having such a <code>Timer</code> object to log the runtime of a few selected functions is more convenient for my purposes.) </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload