Write a Program to Create a Template Function and a Template Class in C++
Templates in C++ are powerful tools that allow you to write generic and reusable code. With templates, you can define functions and classes that work with any data type, eliminating the need to write multiple versions for different types.
C++ supports two types of templates:
- Function Templates – for creating type-independent functions.
- Class Templates – for creating generic classes.
🧩 What is a Function Template?
A function template allows you to write a function that can accept arguments of any data type. The compiler automatically replaces the template with the correct type during compilation.
🧱 What is a Class Template?
A class template allows you to create a generic class that can handle data members of any type. This is useful for data structures like stacks, queues, arrays, etc., which should work with different data types.
🧑💻 C++ Program Demonstrating Function and Class Templates
#include <iostream>
using namespace std;
// Function template
template <typename T>
T findMax(T a, T b) {
return (a > b) ? a : b;
}
// Class template
template <class T>
class Calculator {
private:
T num1, num2;
public:
Calculator(T a, T b) {
num1 = a;
num2 = b;
}
T add() {
return num1 + num2;
}
T multiply() {
return num1 * num2;
}
};
int main() {
// Using function template
cout << "Max of 10 and 20: " << findMax(10, 20) << endl;
cout << "Max of 5.5 and 2.3: " << findMax(5.5, 2.3) << endl;
// Using class template with int
Calculator<int> intCalc(4, 5);
cout << "Integer Addition: " << intCalc.add() << endl;
cout << "Integer Multiplication: " << intCalc.multiply() << endl;
// Using class template with float
Calculator<float> floatCalc(3.5, 2.5);
cout << "Float Addition: " << floatCalc.add() << endl;
cout << "Float Multiplication: " << floatCalc.multiply() << endl;
return 0;
}
🖨️ Output
Max of 10 and 20: 20
Max of 5.5 and 2.3: 5.5
Integer Addition: 9
Integer Multiplication: 20
Float Addition: 6
Float Multiplication: 8.75
🔍 Explanation
1. The function template `findMax` works for both `int` and `float` types.
2. The class template `Calculator` is instantiated twice: once with `int` and once with `float`.
3. This code demonstrates how templates reduce redundancy and promote code reusability.
🧠 Why Use Templates?
- Avoid code duplication.
- Promote type-safety.
- Enable generic programming.
- Widely used in STL (Standard Template Library).
🎯 Conclusion
C++ templates are a cornerstone of generic programming. Whether it's writing a function to find the maximum of two values or building reusable data structures, templates make your code flexible and powerful. Once you get comfortable with them, you’ll notice significant improvements in both efficiency and scalability of your programs.
Comments
Post a Comment