以下回调类是“可调用事物”的通用包装器。我真的很喜欢它的 API,它没有模板而且非常干净,但在底层有一些我无法避免的动态分配。
有没有什么办法可以去掉下面代码中的new和delete,同时保持回调类的语义和API?我真希望我能。
需要的东西:
// base class for something we can "call"
class callable {
public:
virtual void operator()() = 0;
virtual ~callable() {}
};
// wraps pointer-to-members
template<class C>
class callable_from_object : public callable {
public:
callable_from_object(C& object, void (C::*method)())
: o(object), m(method) {}
void operator()() {
(&o ->* m) ();
}
private:
C& o;
void (C::*m)();
};
// wraps pointer-to-functions or pointer-to-static-members
class callable_from_function : public callable {
public:
callable_from_function(void (*function)())
: f(function) {}
void operator()() {
f();
};
private:
void (*f)();
};
回调类:
// generic wrapper for any callable
// this is the only class which is exposed to the user
class callback : public callable {
public:
template<class C>
callback(C& object, void (C::*method)())
: c(*new callable_from_object<C>(object, method)) {}
explicit callback(void (*function)())
: c(*new callable_from_function(function)) {}
void operator()() {
c();
}
~callback() {
std::cout << "dtor\n"; // check for mem leak
delete &c;
}
private:
callable& c;
};
一个 API 示例:
struct X {
void y() { std::cout << "y\n"; }
static void z() { std::cout << "z\n"; }
} x;
void w() { std::cout << "w\n"; }
int main(int, char*[]) {
callback c1(x, &X::y);
callback c2(X::z);
callback c3(w);
c1();
c2();
c3();
return 0;
}
非常感谢 !!:-)