Template in C++
Templates in C++ allow you to construct generic code that can deal with multiple data types without having to replicate the code for each one. In C++, templates are fundamental for constructing flexible and reusable classes and functions. In C++, there are two types of templates: function templates and class templates.
1. Function Templates:
Function templates allow you to create generic functions that can operate on different data types. You define a function template by specifying a placeholder for the data type. Here's a basic example of a function template that swaps two values of any data type:
#include<iostream.h>
#include<conio.h>
template<class T>
void display(T x,T y)
{
T result;
result=x+y;
cout<<"Addition is\n"<<result<<endl;
}
void main()
{
clrscr();
display(4,5);
display(5.7,6.7);
getch();
}
2. Class Templates:
Class templates allow you to define generic classes. You can create a class template with one or more template parameters. Here's a simple example of a class template for a stack data structure:
#include<iostream.h>
#include<conio.h>
template<class T>
class A
{
T a;T b;
public:
void display();
void print();
};
template<class T>
void A<T>::display()
{
cout<<"enter the value of a\n";
cin>>a;
cout<<"Enter the value of b\n";
cin>>b;
}
template<class T>
void A<T>::print()
{
cout<<a<<endl<<b;
}
void main()
{
clrscr();
A<int> a1;
a1.display();
a1.print();
getch();
}