This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Tuesday, February 28, 2023

What is a template and why do we use Template in OOP? WAP to swap to variables using Function Template.

 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:

#include <iostream>
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:

After Swapping:
x = 20, y = 10
p = 6.28, q = 3.14
c1 = B, c2 = A

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget