With “hooking” I mean the ability to non-intrusively override the behavior of a function. Some examples:
- Print a log message before and/or after the function body.
- Wrap the function body in a try catch body.
- Measure duration of a function
- etc…
I have seen different implementations in various programming languages and libraries:
- Aspect Oriented Programming
- JavaScript’s first class functions
- OOP decorator pattern
- WinAPI subclassing
- Ruby’s
method_missing - SWIG‘s
%exceptionkeyword which is meant to wrap all functions in a try/catch block can be (ab)used for the purpose of hooking
My questions are:
- IMO this is such an incredibly useful feature that I wonder why it has never been implemented as a C++ language feature. Are there any reasons that prevent this from being made possible?
- What are some recommended techniques or libraries to implement this in a C++ program?
If you’re talking about causing a new method to be called before/after a function body, without changing the function body, you can base it on this, which uses a custom
shared_ptrdeleter to trigger the after-body function. It cannot be used fortry/catch, since the before and after need to be separate functions using this technique.Also, the version below uses
shared_ptr, but with C++11 you should be able to useunique_ptrto get the same effect without the cost of creating and destroying a shared pointer every time you use it.