Overloading a function means we can have same name to the function but different parameters.
Overloading
of Template Functions
•
Overloading a function means we can have
same name to the function but different parameters. When we overload a template
function ‒
1.
We write a general template function
2.
Another template function with different parameters
3.
Or a regular function that takes precedence in specific cases.
•
Following C++ program shows how to
overload template function ‒
#include <iostream>
using namespace std;
template<typename T>
T add(T a,T b) {
return a+b;
}
template<typename T>
T add(T a,T b,T c){
return a+b+c;
}
int main()
{
cout<<add(10,20)<<endl;
cout<<add(10,20,30);
return 0;
}
Output
30
60
Example:1
Create a
function template called 'add' that takes two arguments of the same type and
returns their sum. This template should work for integers, floating‒point
numbers and other types that support the + operator. In addition to the
template, write a normal (non‒template) function add that specifically handles
string concatenation.
Solution :
#include<iostream>
using namespace std;
string add(string s1,string s2){
cout<<"Normal
Function"<<endl;
return s1+s2;
}
template<typename T>
T add(T a,T b){
cout<<"Template
Function"<<endl;
return a+b;
}
int main() {
cout<<add(2,3)<<endl;
cout<<add(10.20,11.22)<<endl;
cout<<add(string("Jay
"),string(" Hind!!!"))<<<endl;
return 0;
}
Template Function
5
Template Function
21.42
Normal Function
Jay Hind!!!
Object Oriented Programming: Chapter 5: Templates and Exception Handling : Tag: Oops, Computer Programming : C++ Object Oriented Programming - Overloading of Template Functions
Object Oriented Programming (OOPs)
CS25C07 2nd Semester CSE, CSE(CY) Depts | 2025 Regulation | 2nd Semester 2025 Regulation
English Essentials II
EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation
Tamils and Technology தமிழர்களும் தொழில்நுட்பமும்
UC25H02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation
Linear Algebra
MA25C02 2nd Semester | 2025 Regulation
Applied Physics (CSIE) II
PH25C03 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation
Digital Principles and Computer Organization
CS25C06 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation
Basic Electrical and Electronics Engineering
EE25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation
Object Oriented Programming (OOPs)
CS25C07 2nd Semester CSE, CSE(CY) Depts | 2025 Regulation | 2nd Semester 2025 Regulation
Re-Engineering for Innovation
ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation
Object Oriented Programming (OOPs) - Laboratory
CS25C07 2nd Semester CSE, CSE(CY) Depts | 2025 Regulation | 2nd Semester 2025 Regulation