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.
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.
Instead I want that postFunction call to come automatically when I call some Foo's member function. Is it possible? It would help maintenance..
Might be a case for RAII! Dun-dun-dunnn!
struct f1 {
  f1(Foo& foo) : foo(foo) {} // pre-function, if you need it
  void operator()(){} // main function
  ~f1() {} // post-function
private:
  Foo& foo;
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With