15_Templates_Pgms
15_Templates_Pgms
Introduction
Template is one of the new features of C++. It enables the calling of only one
function with generic interface but different types associated with the call.
Templates help in enclosing a class or a function in another canvas called
template. The purpose is to define a class or function with generic data types. Then
the defined generic type can be substituted with specific types such as int, float,
double or char during actual use.
A template can be considered as a kind of macro.
Function Template
To create a function template, we have to enclose the function in a template
and declaring a generic data type, which can be called by any name such as T.
The entire piece of code is called a function template. T is a generic data type.
The template function is one, which has parameterized at least one of the data types of
the arguments. Some compiler will only allow class in place of typename as given
below:
#include<iostream>
using namespace std;
int main()
{
add(3,4);
add(7.0f,2.0f);
add(3.6,7.3);
}
M.Anand 1
#include<iostream>
using namespace std;
M.Anand 2
Class Template
The purpose of the class template is to create a family of classes with varying
types of data members.
#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
M.Anand 3
template <typename T>
void Account <T> ::setData(int n,T b)
{
no=n;
bal=b;
}
template<typename T>
void Account <T>::display()
{
cout<<"\nAccount No.: "<<no;
cout<<"\nBalance : "<<bal;
}
int main()
{
Account <int> a1;
a1.setData(1003,3000);
Account <double> a2;
a2.setData(1004,5000.50);
a1.display();
a2.display();
}
Multiple Arguments
#include<iostream>
using namespace std;
M.Anand 4
#include<iostream>
using namespace std;
int main()
{
arr<int,5> a1;
a1.getData();
a1.display();
}
M.Anand 5