Function Templates in C++

Another use of templates is in function templates. Generic classes were programmed using class templates. Similar to how generic functions are defined using function templates, multiple data type combinations can use a function regardless of its data type.

Several of the pre-built function templates include, for instance.

max(), min(), sort(), etc.

syntax:

template <class T1, class T2>
data_type function_name(T1 a, T2 b)
{
    //function body
}

The function to calculate the average of two numerical values is an example of a function that is somewhat data type independent. Any data type combination between an integer, float, or double value may now be expected by this function. In order to develop a function that may be used to calculate the average of two numerical values, follow these steps.

#include <iostream>
using namespace std;
 
template <class T1, class T2>
float findAverage(T1 a, T2 b)
{
    float avg = (a + b) / 2.0;
    return avg;
}
 
int main()
{
    float avg = findAverage(5.1, 2);
    cout << avg << endl;
}

Output:

3.55
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in