Templates in C++ are a powerful feature that enable generic programming, allowing functions and classes to operate with various data types without requiring separate implementations for each type. They provide a mechanism for writing reusable code that is type-safe and efficient.
These allow the creation of generic functions that can work with different data types. Instead of writing multiple overloaded functions for different types, a single function template can be defined, and the compiler will generate the appropriate function specialization at compile time based on the type arguments provided.
✅ Example 1: Generic Function to Find Maximum
#include <iostream>
using namespace std;
// Function Template
template <typename T>
T findMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << "Max of 5 and 10: " << findMax(5, 10) << endl;
cout << "Max of 3.2 and 6.7: " << findMax(3.2, 6.7) << endl;
cout << "Max of 'A' and 'Z': " << findMax('A', 'Z') << endl;
return 0;
}
🧠 Explanation: The findMax() function works for int, float, and char types because it is written as a template.
✅ Example 2: Generic Function to Find Average of two numbers
#include<iostream>
using namespace std;
template<class T1, class T2>
float funcAverage(const T1 &a,const T2 &b){
float avg= (a+b)/2;
return avg;
}
int main(){
float a;
a = funcAverage(5.5,2);
cout << "The average of these numbers is "<< a<< endl;
return 0;
}
Practice Question:
int, float, and char data types.These allow the creation of generic classes that can manage data of different types. This is particularly useful for implementing data structures like lists, stacks, queues, or trees, where the underlying data type can vary.
✅ Example 1: Generic Class for Pair
#include <iostream>
using namespace std;
template <class T>
class Pair {
T x, y;
public:
Pair(T a, T b) {
x = a;
y = b;
}
void display() {
cout << "Pair: (" << x << ", " << y << ")" << endl;
}
};
int main() {
Pair<int> intPair(1, 2);
Pair<float> floatPair(3.5, 7.2);
Pair<char> charPair('A', 'Z');
intPair.display();
floatPair.display();
charPair.display();
return 0;
}
🧠 Explanation: The same Pair class can now handle integers, floats, and characters by specifying the data type during object creation.