A template is a C++ feature that allows creating a single code template for a group of related functions or classes that can work with different data types. It enables generic programming and helps to write more flexible and reusable code.
We use templates in OOP to create generic classes and functions that can work with multiple data types without having to write the same code for each data type separately. It reduces the code's redundancy and simplifies maintenance.
Here's a program to swap two variables using Function Template:
using namespace std;
template <typename T>
void swapValues(T &a, T &b) {
T temp = a;
a = b;
b = temp;
}
int main() {
int x = 10, y = 20;
float p = 3.14, q = 6.28;
char c1 = 'A', c2 = 'B';
swapValues(x, y);
swapValues(p, q);
swapValues(c1, c2);
cout << "After Swapping: " << endl;
cout << "x = " << x << ", y = " << y << endl;
cout << "p = " << p << ", q = " << q << endl;
cout << "c1 = " << c1 << ", c2 = " << c2 << endl;
return 0;
}
Output:
p = 6.28, q = 3.14
c1 = B, c2 = A
No comments:
Post a Comment
If you have any doubts, please let me know