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
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.
#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; }
Before Swap A:A | B:B After Swap A:B | B:A Before Swap X:10 | Y:20 After Swap X:20 | Y:10To download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions