前/后函数调用实现 [英] Pre/Post function call implementation
问题描述
我想知道我是否可以以某种方式在C ++中进行函数的前/后调用.我有一个包装器类,其中包含许多函数,在每次包装器函数调用之后,我都应该调用另一个始终相同的函数.
I was wondering if I could do pre/post function call in C++ somehow. I have a wrapper class with lots of functions, and after every wrapper function call I should call another always the same function.
所以我不想将postFunction()调用放到每个这样的函数中:
So I do not want to put that postFunction() call to every single one of the functions like this:
class Foo {
f1();
f2();
f3();
.
.
.
fn();
}
void Foo::f1() {
::f1();
postFunction();
}
void Foo::f2() {
::f2();
postFunction();
}
etc.
相反,当我调用某些Foo的成员函数时,我希望postFunction调用自动进行.是否可以?这将有助于维护.
Instead I want that postFunction call to come automatically when I call some Foo's member function. Is it possible? It would help maintenance..
推荐答案
struct f1 {
f1(Foo& foo) : foo(foo) {} // pre-function, if you need it
void operator()(){} // main function
~f1() {} // post-function
private:
Foo& foo;
}
然后,您只需确保每次希望调用该函数时都创建一个新的临时f1对象.重复使用它显然意味着pre/post函数不会每次都被调用.
Then you just have to make sure to create a new temporary f1 object every time you wish to call the function. Reusing it will obviously mean the pre/post functions don't get called every time.
甚至可以像这样包装它:
Could even wrap it like this:
void call_f1(Foo& foo) {
f1(foo)(); // calls constructor (pre), operator() (the function itself) and destructor (post)
}
您可能会尝试其他方式来构造它,但总的来说,请看是否无法让构造函数/析构函数为您完成繁重的工作.
You might experiment a bit with other ways of structuring it, but in general, see if you can't get constructors/destructors to do the heavy lifting for you.
罗马M的方法也可能是一个好主意.编写一个通用包装器,该包装器将函子或函数指针作为其参数.这样,它可以在调用其参数之前和之后调用pre/post函数
Roman M's approach might be a good idea as well. Write one generic wrapper, which takes a functor or function pointer as its argument. That way, it can call pre/post functions before and after calling its argument
这篇关于前/后函数调用实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!