Templates allow generic programming in C++, enabling functions and classes to work with any data type. They promote code reusability by defining generic types that are specified at compile-time.
Stack class).swap function).int, double).This program demonstrates a class template Box and a function template maximum to handle different data types.
#include <iostream>
#include <string>
using namespace std;
// Function template
template <typename T>
T maximum(T a, T b) {
return (a > b) ? a : b;
}
// Class template
template <typename T>
class Box {
private:
T item;
public:
Box(T i) : item(i) {}
// Member function template (implicitly templated)
T getItem() const {
return item;
}
// Member function to compare with another Box
bool isLarger(const Box<T>& other) const {
return item > other.item;
}
};
int main() {
// Using function template
cout << "Maximum of 5 and 3: " << maximum(5, 3) << endl;
cout << "Maximum of 2.5 and 4.7: " << maximum(2.5, 4.7) << endl;
// Using class template
Box<int> intBox(10);
Box<int> anotherIntBox(5);
cout << "Int Box Item: " << intBox.getItem() << endl;
cout << "Is intBox larger than anotherIntBox? " << (intBox.isLarger(anotherIntBox) ? "Yes" : "No") << endl;
Box<string> strBox("Apple");
Box<string> anotherStrBox("Banana");
cout << "String Box Item: " << strBox.getItem() << endl;
cout << "Is strBox larger than anotherStrBox? " << (strBox.isLarger(anotherStrBox) ? "Yes" : "No") << endl;
return 0;
}
Explanation:
Function Template: maximum<T> compares two values of any type T (e.g., int, double).
Class Template: Box<T> stores an item of type T and provides a member function isLarger to compare items.
Template Arguments: Instantiated with int and string types.
Sample Output:
Maximum of 5 and 3: 5
Maximum of 2.5 and 4.7: 4.7
Int Box Item: 10
Is intBox larger than anotherIntBox? Yes
String Box Item: Apple
Is strBox larger than anotherStrBox? No
Overloading function templates involves defining multiple template functions with the same name but different parameter lists or providing a specialized version for specific types. This allows tailored behavior for certain data types while maintaining generic functionality.