Template Example in C++


The program demonstrates the use of function templates and multiple template parameters.

  • maximum is a template function that returns the maximum of two values. It takes two arguments of the same type T and returns the maximum of them.
  • add is another template function that takes two arguments of different types T and R, adds them and displays the result.
  • In main, the program first uses maximum to find the maximum of two integers and the maximum of two floats. Then, it uses add to add an integer and a double.

Source Code

#include<iostream>
using namespace std;
template <class T>
T maximum(T x, T y)
{
    return x>y?x:y;
}
template <class T,class R>
void add(T x,R y)
{
    cout<<"Adding Int Double "<<x+y<<endl;
}
int main()
{
    cout<<"Integer Max "<<maximum(10,50)<<endl;
    cout<<"Float Max "<<maximum(10.5,5.0)<<endl;
    add(10.5,5);
    return 0;
}
To download raw file Click Here

Output

Integer Max 50Float Max 10.5Adding Int Double 15.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