Function templates are used when you need to perform similar operations on various data types, for example, searching for a maximum element in the array. The main advantage of applying the templates is that you do not have to code a separate overload for each type. Instead of declaring multiple overloads of each type
we need to write only one template function
to use it in your code:
Here, the T formal parameter specifying a type of used data is replaced with an actually applied type during compilation, i.e. the compiler automatically generates a separate function for each type – double, datetime, etc. MQL5 also allows you to develop class templates using all the advantages of the approach.
A class template is declared using the template keyword followed by angle brackets<> enumerating the list of formal parameters with the typename keyword. This entry informs the compiler that it deals with a generic class with the T formal parameter defining a real variable type when implementing a class. For example, let's create a vector class for storing an array with T type elements:
Next, let's apply different methods to create three TArray objects in the program for working with various types
Script execution results:
Now, we have 3 vectors with different data types: double, int and string.
Class templates are well suited for developing containers – objects designed for encapsulating other objects of any type. Container objects are collections already containing objects of one certain type. Usually, working with stored data is instantly built into the container.
For example, you can create a class template that does not allow accessing an element outside the array, thus avoiding the "out of range" critical error.
Please note that template declaration should also be used when describing methods outside the class declaration:
Class and function templates allow you to define multiple comma-separated formal parameters, for example, Map collection for storing "key – value" pairs: