Overloading a template function in C++

As you might know, defining several functions with the same name by changing no of arguments, order of arguments, and data type is called overloading

But wait!

Did you know?

we can also overload the template function as shown in the below example

#include <iostream>
using namespace std;
template<class T>
T sum(T a, T b)//first template function having 2 arguments
{
    return a+b;
}
template<class T>
T sum(T a, T b,T c)//second  template function having 3 arguments
{
    return a+b+c;
}
int main()
{
    cout <<sum(20,30) << endl;//Calling the first template function
    cout <<sum(2.3,3.9) << endl;//Calling the first template function
     cout <<sum(2.3,3.9,4.9) << endl;//Calling the second template function
    return 0;
}

Output

50
6.2
11.1

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.