WAP to Add two number using template
Objective
Write a C++ program to add two numbers of any data type using a Class Template.
Algorithm / Approach
- Define a template before the class:
template<class T>. - Use the generic placeholder
Tinstead ofintorfloatinside the class. - Create an
add(T a, T b)function that returnsa+b. - In
main(), instantiate the class while specifying the exact type in angle brackets:Test<double> t;.
main.cpp
#include<iostream>
using namespace std;
template< class T>
class Test {
public :
void add(T a, T b) {
T c;
c = a+b;
cout<<"Sum = "<< c<< endl;
}
};
int main() {
Test< double > t;
t.add(5,6);
t.add(45.32,34.34);
return 0;
}
Expected Output
Sum = 11 Sum = 79.66
Explanation of the Program
- Templates are the foundation of Generic Programming in C++. They allow you to write a single class or function that works identically for integers, floats, doubles, or even custom objects.
- When you write
Test<double> t;, the C++ compiler creates a brand new hidden version of the class in the background where every genericThas been replaced withdouble.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)