In this C++ tutorial, we explain how to write a C++ template function that will return a maximum value of two given numbers. Here, the numbers provided to the function can be of arbitrary data types. Let us tackle this problem immediately.
Template C++ Function for Finding Max Value
The template function definition is given below.
template<typename T>
T maxFunction(T a, T b)
{
if (a>= b)
{
return a;
}
else
{
return b;
}
}
Here, to define a template function, we first need to use
template<typename T>
This means that we are defining a template function where T will be used to denote a generic data type that the function will accept. Then, we define the function using T as a data type of the input arguments of the function:
T maxFunction(T a, T b)
{
if (a>= b)
{
return a;
}
else
{
return b;
}
}
The complete program together with a driver main function is given below
/*
PROBLEM: Define a C++ template function that returns
the maximum number of two given numbers of the same data type.
*/
#include<iostream>
#include<cstdlib>
using namespace std;
template<typename T>
T maxFunction(T a, T b)
{
if (a>= b)
{
return a;
}
else
{
return b;
}
}
int main()
{
float n1=4.7;
float n2=5.1;
float n3;
n3=maxFunction<float>(n2,n1);
cout<<"The maximum value is "<<n3<<endl;
return 0;
}
We define two floats, and to call the function we use
n3=maxFunction<float>(n2,n1);
It is very important to specify the type of the data type that our template function will accept. We do that by using “<float>”. Here, instead of “<float>” you can use also “<int>” or any other data type to notify the compiler of the data type that the function should accept.