Speed up development with full-stack environments for every branch.

Learn More

Simple Addition Function Using Templates [C++]

979 Runs 14026 Views 2163 Copies


rizwan34 37

published 4 years ago

//including header of the library that contains standard input and output functions in std namespace
#include <iostream>
//including header of the library that contains getchar() function
#include <stdio.h>

/*cin and cout functions are in "std" namespace so we are telling our compliler that we will use functions
 from std namespace. If we do not include name space we can still use functions inside std namespace but 
 for that we will have to write "std::" before every function that is in std namespace. like line 16 
using namespace std;

//prototype for templated function given below
template <class type> type add(type num1, type num2);

int main ()
  // Taking input for number 1 for addition
  std::cout << "Please enter integer 1 : ";
  int num1;
  cin >> num1;
  // Taking input for number 2 for addition
  cout << "Please enter integer 2 : ";
  int num2;
  cin >> num2;
  //calling the templated function for integers and getting result in variable "answer" 
  int answer = add(num1, num2);
  //displaying the answer
  cout << "The sum of " << num1 << " & " << num2 << " = " << answer;

  //prevents console from closing immediately by taking a character as input

  // Returing from main function.0 indicates successful termination of the program
  return 0;

//Templated class that takes two same type of arguments and return their sum as type of arguments
// for example, sum of integer and integer is also an integer
template <class type> type add(type num1, type num2)
  //summing and saving result in variable "result" of same type as that of arguments 
  type result = num1 + num2;
  return result;
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).