Decorator for a class method

后端 未结 3 1578
南方客
南方客 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:07

    1. Change measure to a function template to allow you to use any callable, not just a function.

    2. Use a lambda function in run.


    #include 
    #include 
    #include 
    
    template 
    void measure(F f) {
        time_t tBegin = time(NULL);
        f();
        time_t tEnd = time(NULL);
        std::cout << "Duration: " << (tEnd - tBegin) << " sec" << std::endl;
    }
    
    class Myclass {
    private:
        double _d;
    
    public:
        Myclass(double d) : _d(d) {}
    
        void run() {
            measure([=](){m();});
        }
    
        void m() const {
            usleep(1000000 * _d);
        }
    };
    
    int main() {
        Myclass obj(2.0);
        obj.run();
        return 0;
    }
    

    Since, you are not allowed to modify measure, you can use a helper class template and a function template to make it possible for you to use any callable.

    #include 
    #include 
    #include 
    
    void measure(void (*f)()) {
        time_t tBegin = time(NULL);
        f();
        time_t tEnd = time(NULL);
        std::cout << "Duration: " << (tEnd - tBegin) << " sec" << std::endl;
    }
    
    template 
    struct MeasureFunctor
    {
       static F* f_;
       static void run(){(*f_)();}
    };
    
    template  F* MeasureFunctor::f_ = nullptr;
    
    template 
    void measure(F f) {
       MeasureFunctor::f_ = &f;
       measure(MeasureFunctor::run);
    }
    
    class Myclass {
    private:
        double _d;
    
    public:
        Myclass(double d) : _d(d) {}
    
        void run() {
            measure([=](){m();});
        }
    
        void m() const {
            usleep(1000000 * _d);
        }
    };
    
    int main() {
        Myclass obj(2.0);
        obj.run();
        return 0;
    }
    

提交回复
热议问题