Function template overriding in C++

Suppose you would like to write a myMax() function template that returns a minimum of two numbers with any data type

But, what if

if you like the myMax() template function to behave in one way for all the data types except one?

In this situation, we can override the myMax() function template for that specific data type

in other words, we need to provide a non-templated function  for that type

#include <iostream>
using namespace std;
// One function works for all data types.
template <class T>
 T myMax(T x, T y)
{
    return (x > y) ? x : y;
}
int main()
{
    int i=0,j=20;
    // Call myMax for int
    cout << myMax(i, j) << endl;
    // call myMax for double
    double d=1.1,e=9.11;
    cout << myMax(d, e) << endl;
    // call myMax for char
    char ch='A', dh='Z';
    cout << myMax(ch, dh) << endl;
    return 0;
}

Output

20
9.11
Z

To demonstrate, let us say we would like the data type double should use different logic than the myMax() function template then, in that case, we can override it as shown below

#include <iostream>
using namespace std;
// One function works for all data types.
template <class T>
 T myMax(T x, T y)
{
    return (x > y) ? x : y;
}
//Function template overriding
 double myMax(double x, double y)
{
   return (x > y) ? y : x;
}
int main()
{
    int i=0,j=20;
    // Call myMax for int
    cout << myMax(i, j) << endl;
    // call myMax for double
    double d=1.1,e=9.11;
    cout << myMax(d, e) << endl;
    // call myMax for char
    char ch='A', dh='Z';
    cout << myMax(ch, dh) << endl;
    return 0;
}

Output

20
1.1
Z

Mohammed Anees

Hey there, welcome to aneescraftsmanship I am Mohammed Anees an independent developer/blogger. I like to share and discuss the craft with others plus the things which I have learned because I believe that through discussion and sharing a new world opens up

Leave a Reply

Your email address will not be published.