Decorator for a class method

后端 未结 3 1595
南方客
南方客 2020-12-10 17:24

Supposing I have a function (a decorator) that measures the duration of given function:

#include 

void measure(void (*f)()) {
    time_t tBe         


        
3条回答
  •  情书的邮戳
    2020-12-10 18:26

    I also would prefer a lambda (and a std::function as parameter for measure), but since you cannot change that, what about this idea:

    1. Make m() static.
    2. Add a static member to MyClass that takes a reference to the current MyClass instance that is running measure. You must set this everytime before you call m(). Also, think about thread safetiness.
    3. In m() you can then use this reference to get to _d. Alternatively, you could even store the value of _d in a static member var to have it available in m(). Depends on what you actually need from MyClass.

    This approach would allow to measure only one invocation at a time. For parallel execution of multiple measure() calls you could use thread-local-storage for the reference you set in step 2.

提交回复
热议问题