Addition example using Template in C++


The code defines a function template add that takes two parameters of the same type T by reference and returns their sum. The main() function creates four variables i, j, m, and n of types int, int, float, and float, respectively. It then calls the add function twice, passing in pairs of these variables, and prints the result on the console.

The first call to add passes in the integers i and j, and the result of their addition (i.e., i+j) is returned and printed on the console. The second call to add passes in the floats m and n, and the result of their addition (i.e., m+n) is returned and printed on the console.

Source Code

#include<iostream>
using namespace std;
template<class T> T add(T &a,T &b)
{
  T result=a+b;
  return result;
}
int main()
{
  int i=2;
  int j=3;
  float m=2.3;
  float n=1.2;
  cout<<"Addition of i and j is :"<<add(i,j);
  cout<<'\n';
  cout<<"Addition of m and n is :"<<add(m,n);
  return 0;
}
To download raw file Click Here

Output

Addition of i and j is :5
Addition of m and n is :3.5

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples