Tuesday, 4 October 2016

Function Template in C++

Title: Function template in C++
Author: Pavan R Jaiswal
In C++, function templates are functions that serve as a pattern for creating other similar functions. \
The basic idea behind function templates is to create a function without having to specify the exact type(s) 
of some or all of the variables. Instead, we define the function using placeholder types, called template type

Problem Statement: Use function template to check greater number from given two numbers
#include "iostream"
using namespace std;

class FunctionTemplate{
 template <typename type> //keyword "typename" can be replaced by keyword "class" 
  type greaterNumber(type tNum1, type tNum2){
   return (tNum1>tNum2)?tNum1:tNum2;

int main(){
 FunctionTemplate ob;
 int num1=28, num2=25;
 cout<<"\nGreater Integer number is: "<<ob.greaterNumber(num1,num2)<<endl; //function template called for integer

 float fnum1=10.5, fnum2=20.5;
 cout<<"\nGreater Float number is: "<<ob.greaterNumber(fnum1,fnum2)<<endl; //function template called for float
 string fname="Pavan", lname="Jaiswal"; //function template called for string
 cout<<"\nGreater String is: "<<ob.greaterNumber(fname,lname)<<endl;
 return 0;

 ####### OUTPUT ########
[pavan@localhost Programs]$ g++ FunctionTemplate.cpp -o OutputFile
[pavan@localhost Programs]$ ./OutputFile 

Greater Integer number is: 28

Greater Float number is: 20.5

Greater String is: Pavan
[pavan@localhost Programs]$ 

1. http://www.learncpp.com/cpp-tutorial/141-function-templates/ 
2. https://www.tutorialspoint.com/cplusplus/cpp_templates.htm 

No comments: