In short, it is a function that is called. If you pass a function pointer (address) as a parameter to another function, and when this pointer is used to call the function it points to, we say this is
.
Why use it?
Because the caller and the callee can be separated. The caller doesn't care who the callee is, all it needs to know is that there is a called function with a certain prototype and certain restrictions (such as a return value of int).
If you want to know what the callback function does in practice, let’s first assume that there is a situation where we want to write a library that provides certain
implementations, such as
, quick sort, shell sort, shake sort, etc., but in order to make the library more versatile, I don’t want to embed sorting logic in the function, and let users implement the corresponding logic; or, I want the library to be used for a variety of
( int, float, string), what should we do at this time? You can use
and make callbacks.
Callbacks can be used for notification mechanisms. For example, sometimes a timer needs to be set in the program. Every time a certain time is reached, the program will receive a corresponding notification, but the implementer of the notification mechanism knows nothing about our program. At this time, we need to have a specific prototype
, and use this pointer to perform a callback to notify our program that the event has occurred. In fact, the SetTimer() API uses a callback function to notify the timer, and if no callback function is provided, it will also send a message to the program's
.
Another
that uses the callback mechanism is EnumWindow(), which enumerates all top-level windows on the screen, calls a program-provided function for each window, and passes the window's handler. If the callee returns a value, continue iteration, otherwise, Exit. EnumWindow() doesn't care where the callee is or what the callee did with the handler it passed, it only cares about the return value because based on the return value it will continue execution or exit.
In any case, the callback function is inherited from the C language. Therefore, in C++, callbacks should only be used when establishing an interface with C code or dealing with an existing callback interface. function. Except for the above cases, virtual methods or functors should be used in C++ instead of callback functions.
The above is the detailed content of When to use callback function?. For more information, please follow other related articles on the PHP Chinese website!