Making a call to the Pre / Post function

I was wondering if I can somehow make a call to the pre / post function in C ++. I have a wrapper class with many functions, and after each call to the wrapper function, I must always call the other one the same function.

Therefore, I do not want this call to postFunction () to call each of the following functions:

class Foo {
    f1();
    f2();
    f3();
    .
    .
    .
    fn();
}

void Foo::f1() {
    ::f1();
    postFunction();
}

void Foo::f2() {
    ::f2();
    postFunction();
}

etc.

Instead, I want the postFunction call to be executed automatically when I call some member function Foo. Is it possible? This will help maintenance.

+3
source share
5 answers

Maybe 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;
}

f1 , . , , , pre/post .

:

void call_f1(Foo& foo) {
  f1(foo)(); // calls constructor (pre), operator() (the function itself) and destructor (post)
}

, , , , / .

Roman M . , . , pre/post

+11

, , pre\post .

Foo::caller ( function* fp ) {
   preCall ();
   fp (...);
   postCall ();

}
+5
+3

, , , - .

, , , -. Foo, IFoo. -, -

class IFoo { 
public:
  void Bar();  
}

class FooWrapper: public IFoo {
public:
  FooWrapper( IFoo* pFoo ) {
    m_pFoo = pFoo;
  }
  void Bar() {
    PreBar();
    m_pFoo->Bar();
    PostBar();
  }
}
+2

, ++ B.Stroustrup.

++

This document provides a simple, general, and effective solution to an old problem. '' Wrapping calls an object in pairs of prefix and suffix code. The solution is also non-intrusive, applies to existing classes, allows the use of several prefix / suffix pairs, and can be implemented in 15 simple lines of the C ++ standard. A durable version of the wrapper is also presented. The requirement of efficiency is confirmed by measurement.

0
source

Source: https://habr.com/ru/post/1711381/


All Articles