Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to Add two number using template

C++ Code Example — Exception Handling

ADVERTISEMENT

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

  1. Define a template before the class: template<class T>.
  2. Use the generic placeholder T instead of int or float inside the class.
  3. Create an add(T a, T b) function that returns a+b.
  4. 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&lt;double&gt; t;, the C++ compiler creates a brand new hidden version of the class in the background where every generic T has been replaced with double.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT