Examples of implementation of template functions and overloaded template functions. Processing of single elements. Processing arrays
This topic demonstrates the use of the C++ template engine to implement overloaded template functions. Solutions to several well-known tasks are given. Using these examples, you can learn to develop your own template functions that process both single elements and element arrays.
Contents
- 1. Examples of implementations of template functions
- 2. Examples of implementations of overloaded template functions
- 2.1. An example of overloading a template function of maximum search between 2, 3, 4 parameters
- 2.2. An example of overloading a template function that determines the number of positive elements for arrays of different dimensions
- 2.3. An example of overloading a template function that forms dynamic arrays of different dimensions
- Related topics
Search other websites:
1. Examples of implementations of template functions
1.1. An example of a template function for finding the maximum between two elements
The example implements the template of the Max() function (template function) for the generalized type T, which determines the maximum value between the two parameters a and b.
#include <iostream> using namespace std; // Topic. Template Functions // Maximum value search function template between two values template <class T> T Max(T a, T b) { if (a > b) return a; return b; } void main() { // Demonstration of a template function Max() // 1. For int type int i1, i2, maxInt; // 1.1. Input integers i1, i2 cout << "Enter integers:" << ::endl; cout << "i1 = "; cin >> i1; cout << "i2 = "; cin >> i2; // 1.2. Calling the template function Max(T, T) => Max(int, int) maxInt = Max(i1, i2); // 1.3. Display the result cout << "maxInt = " << maxInt << endl; // 2. For float type float f1, f2, maxFloat; // 2.1. Ввод чисел f1, f2 cout << "Enter floats:" << ::endl; cout << "f1 = "; cin >> f1; cout << "f2 = "; cin >> f2; // 2.2. Calling the template function Max(T, T) => Max(float, float) maxFloat = Max(f1, f2); // 2.3. Display the result cout << "maxFloat = " << maxFloat << endl; // 3. For char types char c1, c2, maxChar; // 3.1. Display the values c1, c2 cout << "Enter chars:"; cout << "\nc1 = "; cin >> c1; cout << "c2 = "; cin >> c2; // 3.2. Calling the template function Max(T, T) => Max(char, char) maxChar = Max(c1, c2); // 3.3. Display the result cout << "maxChar = " << maxChar << endl; system("pause"); }
The result of the program:
Enter integers: i1 = 2 i2 = 7 maxInt = 7 Enter floats: f1 = 2.56 f2 = 3.55 maxFloat = 3.55 Enter chars: c1 = f c2 = q maxChar = q
⇑
1.2. An example of a template function for calculating the average of array elements
In the example, the template function Average() was developed to search for the arithmetic mean of two-dimensional array values.
Since the Average() function calculates the arithmetic average of the values of the elements of the array, this array must be passed to the function. The size of the array is also passed to the function. The text of the application created using the Console Application template is as follows.
#include <iostream> using namespace std; // Topics. Function templates // The keyword typename or class is used. // The function receives 2 parameters: // - count - the number of items in Array[]; // - Array[] - array of items of type T. template <typename T> double Average(int count, T Array[]) { // 1. Declare an avg variable of type double, // since the average is a real number double avg; // 2. Zero the value of the variable avg before summing avg = 0.0; // 3. Calculate the sum of items of Array[] for (int i = 0; i < count; i++) avg += Array[i]; // 4. Calculate the average avg /= count; // 5. Return the value of avg return avg; } void main() { // Demonstration of template function Average(int, T[]) // 1. For int types // 1.1. Declare a variables int countInt = 5; // the number of items in the array AI int AI[] = { 2, 4, -1, 70, 18 }; // initializing the array AI double avg; // average - result // 1.2. Call the template function Average(int, T[]) => Average(int, int[]) avg = Average(countInt, AI); // 1.3. Display the result cout << "Average for AI = " << avg << endl; // 2. For float type // 2.1. Declaration the variables int countFloat = 6; float AF[] = { 2.8f, 3.2f, -1.4f, 0.5f , 1.2f, 10.2f }; // 2.2. Call the template function Average(int, T[]) => Average(int, float[]) avg = Average(countFloat, AF); // 2.3. Diaplay the result cout << "Average for AF = " << avg << endl; }
The result of the program
Average for AI = 18.6 Average for AF = 2.75
⇑
1.3. An example of the implementation of template functions for copying an array and displaying an array on the screen
Task. Write a template for the CopyArray() function that copies the elements of the one-dimensional array A[] to the array B[]. The sizes of arrays are considered the same. The output of the resulting array must be implemented in the template function Print().
The text of the software solution is as follows.
#include <iostream> using namespace std; // The template of CopyArray() function // The function copies one array to another: A[] => B[] // Parameters: // - count - number of elements in arrays; // - A[] - source array, array elements are of type Type; // - B[] - destination array, array elements are of type Type. template <class Type> void CopyArray(int count, Type A[], Type B[]) { for (int i = 0; i < count; i++) { B[i] = A[i]; } } // The template of Print() function. // The function displays an array of generic type TT on the screen. // Parameters: // - count - the number of items in the array; // - Array[] - an array of items of type TT. template <class TT> void Print(int count, TT Array[]) { cout << "Items of array:" << ::endl; for (int i = 0; i < count; i++) { cout << Array[i] << "\t"; } cout << endl; } void main() { // Using the CopyArray() template Function // 1. Declare a common constant const int MAX_ITEMS = 10; // 2. Demonstration for int type // 2.1. Declare two arrays of int type int AI[] = { 1, -3, 2, 4, 5 }; // the source array int BI[MAX_ITEMS]; // destination array // 2.2. Call the template function CopyArray() CopyArray(5, AI, BI); // 2.3. Call the template function Print() cout << "Array BI[]. "; Print(5, BI); // 3. Demonstration for float type // 3.1. Declare two arrays of float type float AF[] = { -2.4, 3.8, -1.5, 7.75 }; float BF[MAX_ITEMS]; // 3.2. Call the template function CopyArray() CopyArray(4, AF, BF); // 3.3. Call the template function Print() cout << "Array BF[]. "; Print(4, BF); }
The result of the program
Array BI[]. Items of array: 1 -3 2 4 5 Array BF[]. Items of array: -2.4 3.8 -1.5 7.75
⇑
2. Examples of implementations of overloaded template functions
2.1. An example of overloading a template function of maximum search between 2, 3, 4 parameters
The example implements the overload of the template function Max(), which calculates the maximum value between the received parameters. The function is implemented for two, three and four parameters.
The text of the demo program is as follows:
#include <iostream> using namespace std; // Topic. Overloading function templates // Overloading a template function named Max(). // 1. The template of function Max(T, T), // that determine a maximum between 2 parameters template <class T> T Max(T a, T b) { if (a > b) return a; return b; } // 2. The template of function Max(T, T, T), // that determine a maximum between 2 parameters template <class T> T Max(T a, T b, T c) { T maximum = a; if (maximum < b) maximum = b; if (maximum < c) maximum = c; return maximum; } // 2. The template of function Max(T, T, T, T), // that determine a maximum between 4 parameters template <class T> T Max(T a, T b, T c, T d) { T maximum = a; if (maximum < b) maximum = b; if (maximum < c) maximum = c; if (maximum < d) maximum = d; return maximum; } void main() { // Demonstration of overloaded template function Max() // 1. For two parameters int i1, i2, maxInt_2; // 1.1. Input integers i1, i2 cout << "Enter integers:" << ::endl; cout << "i1 = "; cin >> i1; cout << "i2 = "; cin >> i2; // 1.2. Call the template function Max(T, T) => Max(int, int) maxInt_2 = Max(i1, i2); // 1.3. Display the result cout << "maxInt = " << maxInt_2 << endl; // 2. For 3 parametersof float type float f1, f2, f3, maxFloat_3; // 2.1. Input numbers f1, f2, f3 cout << "Enter floats:" << ::endl; cout << "f1 = "; cin >> f1; cout << "f2 = "; cin >> f2; cout << "f3 = "; cin >> f3; // 2.2. Call the template function Max(T, T, T) => Max(float, float, float) maxFloat_3 = Max(f1, f2, f3); // 2.3. Display the result cout << "maxFloat = " << maxFloat_3 << endl; // 3. For 4 parameters of double type double d1, d2, d3, d4, maxDouble; // 3.1. Input values d1, d2, d3, d4 cout << "Enter doubles:"; cout << "\nd1 = "; cin >> d1; cout << "d2 = "; cin >> d2; cout << "d3 = "; cin >> d3; cout << "d4 = "; cin >> d4; // 3.2. Call the template function Max(T, T, T, T) // Max(T, T, T, T) => Max(double, double, double, double) maxDouble = Max(d1, d2, d3, d4); // 3.3. Display the result cout << "maxDouble = " << maxDouble << endl; system("pause"); }
The result of the program:
Enter integers: i1 = 2 i2 = 5 maxInt = 5 Enter floats: f1 = 2.56 f2 = 3.8 f3 = 4.44 maxFloat = 4.44 Enter doubles: d1 = 2.96 d2 = 1.35 d3 = 2.88 d4 = 3.54 maxDouble = 3.54
⇑
2.2. An example of overloading a template function that determines the number of positive elements for arrays of different dimensions
#include <iostream> using namespace std; // Overloading a function template // Declare global constants of static array bounds const int MAX_ITEMS_1 = 10; const int MAX_ITEMS_2 = 10; const int MAX_ITEMS_3 = 10; // The CountItems() function determines the number of positive elements. // 1. Implementation for a one-dimensional array template <typename T> int CountItems(int n, T Array[]) { int count = 0; // result // the loop of calculation of count for (int i = 0; i < n; i++) if (Array[i] > 0) count++; // return the result return count; } // 2. Implementation for two-dimensional array // Parameters: // - m, n - array sizes // - Array - two-dimensional array template <class Type> int CountItems(int m, int n, Type Array[][MAX_ITEMS_2]) { int count = 0; // result // nested loops of calculation k for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (Array[i][j] > 0) count++; // return the result return count; } // 3. Implementation for three-dimensional array // Parameters: // - m, n - array size // - Array - three-dimensional array template <class T> int CountItems(int m, int n, int d, T Array[][MAX_ITEMS_2][MAX_ITEMS_3]) { int count = 0; // result // the loop of calculation count for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) for (int k = 0; k < d; k++) if (Array[i][j][k] > 0) count++; // return the result return count; } void main() { // Demonstration of overloaded template function CountItems() // 1. For one-dimensional array of double // 1.1. Declaring of internal variables double AD[MAX_ITEMS_1] = { 2.5, -1.1, 3.5, 8.2 }; // array initialization int count1; // 1.2. Call the function CountItems(int, double[]) count1 = CountItems(4, AD); // count1 = 3 // 1.3. Display the result cout << "count1 = " << count1 << endl; // 2. For two dimensional array of short type // 2.1. Declare an internal variables short AS[MAX_ITEMS_1][MAX_ITEMS_2] = { { 3, 5, 2}, { 4, 2,-5}, {-1,-2,-3}, { 5,-8,-4} }; int count2; // 2.2. Call the function CountItems(int, int, short[][]) count2 = CountItems(4, 3, AS); // 2.3. Display the result cout << "count2 = " << count2 << endl; // 3. For three-dimensional array of type float. The size of array 2*3*4 // 3.1. Declare an internal variables float AF[MAX_ITEMS_1][MAX_ITEMS_2][MAX_ITEMS_3] { { { 1.2f, -2.3f, -4.4f, 2.5f }, { 4.2f, -3.3f, -1.8f, -0.1f }, { -1.8f, -2.5f, 3.3f, 4.2f } }, { { 4.8f, -1.2f, 3.5f, 8.8f }, { 1.1f, 0.5f, 0.8f, 2.5f }, { 4.6f, 1.3f, -2.2f, 1.8f } } }; int count3; // 3.2. Call the function CountItems(int, int, int, float[][][]) count3 = CountItems(2, 3, 4, AF); // 3.3. Display the result cout << "count3 = " << count3 << endl; }
The result of the program
count1 = 3 count2 = 6 count3 = 15
⇑
2.3. An example of overloading a template function that forms dynamic arrays of different dimensions
Task. Write an overloaded template function FormArray(), which fills the one-dimensional and two-dimensional dynamic arrays with random elements. The output of elements of arrays must be implemented using the overloaded template function PrintArray(), which also has two implementations: for one-dimensional and two-dimensional arrays.
The text of the program created using the Console Application template is as follows:
#include <iostream> #include <time.h> using namespace std; // Overloading the template function FormArray () // 1. Forming a one-dimensional array // Parameters: // - count - the number of elements in the array; // - Array[] - array of elements of type T. template <class T> void FormArray(int count, T* Array) { // 1. Initialize the random number generator srand(time(NULL)); // 2. Write random numbers from 0 to 100 to the array for (int i = 0; i < count; i++) Array[i] = (T)(rand() % 101); } // 2. Forming a two-dimensional array // Parameters: // - m, n - array size; // - Array - two-dimensional array of type T template <class T> void FormArray(int m, int n, T** Array) { // 1. Initialize data srand(time(NULL)); // 2. Fill an array with random values for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) Array[i][j] = (T)(rand() % 101); } // Overloaded template function for outputting an array to a screen // 1. Implementation for one-dimensional array template <class T> void PrintArray(int count, T* A) { cout << "Items of one-dimensional array: " << endl; for (int i = 0; i < count; i++) cout << A[i] << "\t"; cout << endl; } // 2. Implementation for two-dimensional array of type T // Parameters: // - m, n - array size; // - A - two-dimensional array of type T template <class T> void PrintArray(int m, int n, T** A) { cout << "Items of two-dimensional array: " << endl; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << A[i][j] << "\t"; cout << endl; } } void main() { // Demonstration of overloading of function templates // 1. One-dimensional array of type int // 1.1. Declare a dynamic array of integers and its dimension int* AI = nullptr; int count1; // 1.2. Input the array size cout << "count = "; cin >> count1; try { // 1.3. An attempt to allocate memory for an array AI = new int[count1]; } catch (bad_alloc ba) { // If the memory is not allocated, then exit the program // ba.what() - the text of memory allocation system error cout << "Error. " << ba.what() << endl; return; } // 1.4. If the memory is allocated successfully, // then call the template function of forming array items FormArray(count1, AI); // 1.5. Print array on screen PrintArray(count1, AI); // 1.6. After finishing work, release memory for the AI array if (AI!=nullptr) delete[] AI; // 2. Demonstration of a call to FormArray () and PrintArray () // for two-dimensional array of type double // 2.1. Declare variables double** AD = nullptr; // two-dimensional array int m, n; // array dimension // 2.2. Enter the array size cout << "Enter the size of array: " << endl; cout << "m = "; cin >> m; cout << "n = "; cin >> n; // 2.3. Allocate memory for AD array try { // Attempt to allocate memory // for an array of pointers to type double AD = (double**) new double*[m]; // for each element of the array for (int i = 0; i < m; i++) AD[i] = new double[n]; } catch (bad_alloc ba) { cout << "Error. " << ba.what() << endl; return; } // 2.4. Call function FormArray(int, int, T**) => FormArray(int, int, double**) FormArray(m, n, AD); // 2.5. Call function PrintArray(int, int, T**) => PrintArray(int, int, double**) PrintArray(m, n, AD); // 2.6. Release the previously allocated memory if (AD != nullptr) delete[] AD; }
The result of the program
count = 4 Items of one-dimensional array: 97 40 23 95 Enter the size of array: m = 5 n = 6 Items of two-dimensional array: 9 64 86 64 27 55 59 38 100 4 3 74 26 25 22 7 45 62 89 84 48 48 79 56 79 42 49 70 7 73
⇑
Related topics
⇑