Reklama

The use of templates in C++

Our IntArray class provides a good alternative to the built-in array of integers. But life can take arrays for various data types. We can assume, the only difference between array elements of double type from our type of the data is in the ads, the rest of the code matches literally.
To resolve this problem in c++ mechanism templates. Class and function declarations are allowed to use parameterized types. Type parameters are replaced at compile time these types, built-in or user-defined. We can create a template Array class, replacing in the class IntArray elements of type int on a generic type parameter. Later we determine the types-options, substituting them real types int, double and string. The result will be a way to use this specification so, as if we actually defined three different classes for these three data types.
Now can be rewritten as a template class Array:

The keyword template tells, that sets the template, parameters are enclosed in angle brackets (<>). In our case there is only one parameter elemType; the class keyword in front of its name tells, what this option represents a type of.
In specifying template classes Array parameter elemType is replaced by the actual type for each use, as shown in the example:

It defines three instance of the class Array:

What does the compiler, if you saw this ad? Displays the text of the template Array, replacing the parameter elemType the type, specified in each case. Therefore, ads members are becoming in the first case, this kind:

Note, what is it exactly corresponds to the definition of the array IntArray.
For the remaining two cases, we get the following code:

What happens to the member functions? This type is the parameter elemType is replaced by the actual type, however, the compiler does not specify the functions, which are not invoked in any place of the program.
When you run a program this example will give following result:

The template engine can be used in inherited classes. Here is the definition of a template class ArrayRC:

The substitution of actual parameters instead type-parameter elemType happens both in the base, and in derived classes.

Definition behaves exactly the same, as the definition IntArrayRC from the previous section. Change the example usage from the previous section.

First of all, to operator // function swap() also you should make the template valid, we will need to introduce a function swap() template.

Each call to swap() generated appropriate specification, which depends on type of array. Here is the program, using templates Array and ArrayRC:

Reklama