Run Code Before Every Function Call for a Class in C++

后端 未结 9 1240
被撕碎了的回忆
被撕碎了的回忆 2021-02-15 13:08

I would like to run some code (perhaps a function) right before every function call for a class and all functions of the classes that inherit from that class. I\'d like to do t

相关标签:
9条回答
  • 2021-02-15 13:31

    AspectC++ is what you want. I haven't used it myself, but Aspect-Oriented Programming paradigm tries to solve this exact problem.

    0 讨论(0)
  • 2021-02-15 13:32

    The somewhat inconvenient way where to build a wrapper class that takes an object of your base type and calls the surrounding function and then the function that you wanted to call. This would be something like a decorator.

    0 讨论(0)
  • 2021-02-15 13:36

    The best you can do is to declare a set of virtual functions as protected and have the developers inheriting from the class override the virtual functions. The interface used by the base class can be public, which executes the desired code before passing information to the protected virtual method.

    For example:

    class Base {
      public:
        void MyMethod(void) { /* Insert code here */ YourMethod(); }
      protected:
        virtual void YourMethod(void) {}
    };
    

    If the developer knows that he has a specific subclass, he can still bypass your code simply by using a dynamic_cast, and using his own method set. As such, you may want to follow the other suggestions already posted that do not involve the base C++ language.

    0 讨论(0)
提交回复
热议问题