Q10. Demonstrate Function Templates in C++
Question:
Write a program to demonstrate use of function templates.
My Approach
C++ me templates ek bahut powerful feature hai jo code reusability provide karta hai.
Agar hame ek hi logic ko different data types (int, float, double, string) ke liye use karna ho to har type ke liye alag function likhne ki zaroorat nahi hoti.
Bas ek template function likhna hota hai aur wo multiple types ke liye kaam karega.
Program Code
File Name: function_template_demo.cpp
#include <iostream>
using namespace std;
// Template function
template <typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
// Integers
int x = 10, y = 20;
cout << "Max of " << x << " and " << y << " is: " << getMax(x, y) << endl;
// Floats
float p = 12.5, q = 9.8;
cout << "Max of " << p << " and " << q << " is: " << getMax(p, q) << endl;
// Characters
char c1 = 'A', c2 = 'Z';
cout << "Max of '" << c1 << "' and '" << c2 << "' is: " << getMax(c1, c2) << endl;
// Strings (lexicographical comparison)
string s1 = "Apple", s2 = "Banana";
cout << "Max of \"" << s1 << "\" and \"" << s2 << "\" is: " << getMax(s1, s2) << endl;
return 0;
}Sample Output
Max of 10 and 20 is: 20
Max of 12.5 and 9.8 is: 12.5
Max of 'A' and 'Z' is: Z
Max of "Apple" and "Banana" is: BananaExplanation
template <typename T>→ Ye compiler ko batata hai ki function generic hai aur kisi bhi type ke liye kaam karega.getMax(T a, T b)→ Ek hi function integer, float, char aur string ke liye work kar raha hai.- Template ka main fayda code reusability aur type safety hai.
Real-Life Scenario
- Example: Jab tum MCA students ke exam marks compare karte ho (int type).
- Jab tum lab performance percentage compare karte ho (float type).
- Jab tum student ke naam alphabetically compare karte ho (string type).
Ye sab bina alag-alag function likhe, ek hi template function se ho sakta hai.
Conclusion
- Function templates ek hi code ko multiple data types ke liye reusable banate hain.
- Ye approach programming ko efficient aur less error-prone banata hai.
Submitted by:
Intesab Ansari
MCA Student, NMU University
Portfolio: intesab.live
Last updated on