Write a program for function template to find and display the smaller of two numbers of which may be integer or floating point numbers or characters.

Sep 2, 2019

Source code:

//program to find the maximum
//using function template

#include <iostream>
using namespace std;

//function template to find the maximum
template <class Type>
Type get_small(Type t1, Type t2){
    if(t1 < t2){
        return t1;
    }else{
        return t2;
    }
}

int main(){
    int x1 = 20, x2 = 50;
    float y1 = 4.5, y2 = 1.1;
    char ch1 = 'A', ch2 = 'B';
    cout<<"Smaller of integer = "<<get_small(x1, x2)<<endl;
    cout<<"Smaller of floating = "<<get_small(y1, y2)<<endl;
    cout<<"Smaller of character = "<<get_small(ch1, ch2)<<endl;
    return 0;
}

 

Sample run:

Smaller of integer = 20
Smaller of floating = 1.1
Smaller of character = A