Template In C++ Programming


Templates are powerful features of C++ which allows you to write generic programs. In simple terms, you can create a single function or a class to work with different data types using templates. Templates are often used in larger codebase for the purpose of code reusability and flexibility of the programs.

The program demonstrates the use of templates in C++ functions to create a generic function that can be used for multiple data types. The function named swapping takes two parameters of the same data type and swaps their values. The main function uses this swapping function for two different data types, char and int.

The template line before the function definition indicates that the function will be generic and can work with any data type. The T is a placeholder for the actual data type that will be used when the function is called.

In the main function, the variables a and b are of type char, and x and y are of type int. The swapping function is called twice with different parameters, once with a and b, and then with x and y. In each case, the function swaps the values of the two variables and prints the updated values to the console.

This program shows the power and flexibility of templates in C++, allowing for the creation of generic functions that can be used with different data types.

Source Code

#include<iostream>
using namespace std;
//  Templates in C++
template <class T>
void swaping(T &a,T &b)
{
    T t=a;
    a=b;
    b=t;
}
int main()
{
    char a='A',b='B';
    int x=10,y=20;
    cout<<"Before Swap A:"<<a<<" | B:"<<b<<endl;
    swaping(a,b);
    cout<<"After  Swap A:"<<a<<" | B:"<<b<<endl;
 
    cout<<"Before Swap X:"<<x<<" | Y:"<<y<<endl;
    swaping(x,y);
    cout<<"After  Swap X:"<<x<<" | Y:"<<y<<endl;
    return 0;
}
 

Output

Before Swap A:A | B:B
After  Swap A:B | B:A
Before Swap X:10 | Y:20
After  Swap X:20 | Y:10
To download raw file Click Here

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