类方法的装饰器 [英] Decorator for a class method
问题描述
假设我有一个函数(装饰器),用于测量给定函数的持续时间:
Supposing I have a function (a decorator) that measures the duration of given function:
#include <unistd.h>
void measure(void (*f)()) {
time_t tBegin = time(NULL);
f();
time_t tEnd = time(NULL);
cout << "Duration: " << (tEnd - tBegin) << " sec" << endl;
}
我想测量类方法的持续时间。例如:
And I want to measure the duration of a method of a class. For example:
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;
}
这种实现会导致错误:
error: invalid use of non-static member function
C ++中是否有一种方法可以正确实现它?应该不要修改外部函数 measure
,并且所测方法完全是非静态的(它使用实例的数据)。度量应该在方法 run
内。
Is there a way in C++ to implement it correctly? It's supposed not to modify the external function measure
and the measured method is exactly non-static (it uses data of the instance). The measurement should be inside of the method run
.
我需要C ++ 1998/2003 Standard的解决方案。
I need solution for C++ 1998/2003 Standard.
推荐答案
-
将
度量
更改为函数模板,使您可以使用任何可调用的函数,而不仅仅是函数。
Change
measure
to a function template to allow you to use any callable, not just a function.
在 run $ c $中使用lambda函数c>。
#include <iostream>
#include <time.h>
#include <unistd.h>
template <typename F>
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;
}
因为您不是允许修改 measure
,则可以使用助手类模板和函数模板,使您可以使用任何可调用对象。
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 <iostream>
#include <time.h>
#include <unistd.h>
void measure(void (*f)()) {
time_t tBegin = time(NULL);
f();
time_t tEnd = time(NULL);
std::cout << "Duration: " << (tEnd - tBegin) << " sec" << std::endl;
}
template <typename F>
struct MeasureFunctor
{
static F* f_;
static void run(){(*f_)();}
};
template <typename F> F* MeasureFunctor<F>::f_ = nullptr;
template <typename F>
void measure(F f) {
MeasureFunctor<F>::f_ = &f;
measure(MeasureFunctor<F>::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;
}
这篇关于类方法的装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!