The typedef keyword in C++ allows creating user-defined data types. To do this, simply specify a new data type name for an already existing data type. The new data type is not created. A new name for the existing type is defined instead. User-defined types make applications more flexible: sometimes, it is enough to change typedef instructions using substitution macros (#define). User-defined types also improve code readability since it is possible to apply custom names to standard data types using typedef. The general format of the entry for creating a user-defined type:
Here, type means any acceptable data type, while new_name is a new name of the type. A new name is set only as an addition (not as a replacement) to an existing type name. MQL5 allows creating pointers to functions using typedef.
A pointer to a function is generally defined in the following format
where after typedef, the function signature (number and type of input parameters, as well as a type of a result returned by the function) is set. Below is a simple example of creating and applying a pointer to a function:
In this example, the func_ptr variable may receive the sub and add functions since they have two inputs each of int type as defined in the TFunc pointer to the function. On the contrary, the neg function cannot be assigned to the func_ptr pointer since its signature is different.
Pointers to functions allow you to easily create processing of events when creating a user interface. Let's use an example from the CButton section to show how to create buttons and add the functions for handling pressing to them. First, define a pointer to the TAction function to be called by pressing the button and create three functions according to the TAction description.
Then, create the MyButton class from CButton, where we should add the TAction pointer to the function.
Create the CControlsDialog derivative class from CAppDialog, add the m_buttons array to it for storing the buttons of the MyButton type, as well as the AddButton(MyButton &button) and CreateButtons() methods.
Now, we can develop the program using the CControlsDialog control panel having 3 buttons: Open, Save and Close. When clicking a button, the appropriate function in the form of the TAction pointer is called.
The launched application's appearance and button clicking results are provided on the screenshot.
The full source code of the program