A template is a feature in C++ that allows a programmer to create a generic class or function that can work with different types of data. Templates make the code more reusable and allow the programmer to write a single implementation that can be used with multiple data types.
Here is an example program that uses a function template to find the sum of the first and last elements of an array of size N:
using namespace std;
template <typename T>
T sum_first_last(T arr[], int N) {
return arr[0] + arr[N-1];
}
int main() {
cout << "Sum of first and last elements of float array: " << sum_first_last(arr2, n) << endl;
return 0;
}
In the above program, the sum_first_last() function is a template function that takes an array arr of type T and the size of the array N as arguments. The function returns the sum of the first and last elements of the array.
In the main() function, we create two arrays of different types (int and float) and call the sum_first_last() function for each array. The compiler automatically generates two separate versions of the sum_first_last() function for the two different types.
No comments:
Post a Comment
If you have any doubts, please let me know