Templates in C
Templates in C
A template is a
Templates
mechanism that allows you to create
functions and classes that can be reused with every data
types.
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 referred as generic types.
Templates offers us the feature of generic
programming[It is an approach where generic types are
used as parameters in algorithms so that they work for a
variety of suitable data types and data structures].
C++ provides two kinds of templates which can
exhibit generic programming, such as
Class template(or Generic classes)
Function template(or Generic functions)
Templates continued…..
A template can be considered as a kind of macro[i.e.
Expanded at compile time]
The difference is, compiler does type checking before
template expansion. The idea is simple, source code
contains only function/class, but compiled code may
contain multiple copies of same function/class.
Template is defined with a parameter that would be
replaced by a specific data type at the time of actual
use of class or function, the templates are sometimes
called as parameterized classes or functions.
Function templates
Function Templates are used to write a generic
function that can be used for different data types.
Function templates are also known as generic
functions
A function template works in a similar to a
normal function, with one key difference.
A single function template can work with different
data types at once but, a single normal function can
only work with one set of data types.
Normally, if you need to perform identical operations
on more than one types of data, then we need to
create multiple functions with suitable types, which
is a tedious task for the programmers, so the better
approach is to create a generic function(or function
template), when can work on multiple types of data
values with identical operation.
Function template-Syntax
A function template starts with the keyword template
followed by template parameter/s inside < > which is
followed by function declaration.
template <class T>
returntype function_name(arguments of type T )
{
// body of function with type T
………..
}
In the above code, T is a template argument( or
generic type) that accepts different data types (int,
float….etc), and class is a keyword.
You can also use keyword typename instead of class
in the above example.
When, an argument of a data type is passed to the
function, compiler generates a new version of function
for the given data type.
Example1-Function template(WAP to calculate area of square using function template)
#include<iostream>
using namespace std; Output:
template<class T> Square of 3=9
T square(T num)
Square of
{
return (num*num);
5.6=31.36
} Square of
int main() 123.456=15241.4
{
int num1=3;
cout<<"\n Square of "<<num1<<" =
"<<square<int>(num1);
float num2=5.6;
cout<<"\n Square of "<<num2<<" =
"<<square<float>(num2);
double num3=123.456;
cout<<"\n Square of "<<num3<<" =
"<<square<double>(num3);
return 0;
}
Example 2-Function template(WAP to display
minimum of two numbers)
include<iostream> cout<<"enter float value";
using namespace std; cin>>p>>q;
template<class T> cout<<"\nmin of
T min1(T a,T b) integer"<<min1<int>(x,y
);
{
cout<<"\nmin of floating
return(a<b?a:b); value"<<min1<float>(p,q
} );
int main() return 0;
{ }
int x,y; //Output
float p,q; Enter integer values 3 9
cout<<"enter integer Enter float values 1.2 3.4
value"; Min of integer values 3
cin>>x>>y; Min of floating values 1.2
Example 3-Function template(WAP to swap the
values of two variables using function template)
#include<iostream> cout<<"\n Before swapping:";
using namespace std; cout<<"\n inum1="<<inum1<<" and
inum2="<<inum2;
template<class T>
cout<<"\n fnum1="<<fnum1<<" and
void swap1(T &a, T &b) fnum2="<<fnum2;
{ cout<<"\n c1= "<<c1<<" and
T temp=a; c2="<<c2;
a=b; swap1<int>(inum1,inum2);
b=temp; swap1<float>(fnum1,fnum2);
swap1<char>(c1,c2);
}
cout<<"\n\n After Swapping:";
int main()
cout<<"\n inum1="<<inum1<<" and
{ inum2="<<inum2;
int inum1=4,inum2=5; cout<<"\n fnum1="<<fnum1<<" and
float fnum2="<<fnum2;
fnum1=4.8,fnum2=-5.3; cout<<"\n c1= "<<c1<<" and
char c1='A',c2='a'; c2="<<c2;
return 0;
}
Example 4-Function template(WAP to read the values of
array and add their elements using function template)
#include<iostream>
int main()
using namespace std;
{
#define MAX 5
int Array[MAX];
template<class Type>
float Array1[MAX];
Type sum(Type A[])
cout<<"\n Enter the integer
{ array elements : ";
Type Total = 0; read<int>(Array);
for(int i=0;i<MAX;i++) cout<<"\n Sum of elements =
Total += A[i]; "<<sum<int>(Array);
return Total; cout<<"\n Enter the float array
} elements : ";
template<class Type> read<float>(Array1);
void read(Type A[]) cout<<"\n Sum of elements =
{ "<<sum<float>(Array1);
for (int i=0;i<MAX;i++) }
cin>>A[i];
}
Function template with
multiple parameters
We can use more than one generic type in the template
function by using comma to separate the list.
Syntax:
template<class T1, class T2,.....>
return_type function_name (arguments of type T1,
T2....)
{
// body of function.
}
Example-Function template with
multiple parameters
#include<iostream> multiply<int,int>(2,2);
using namespace std;
float num3=7.8;
template<class T1,class T2>
void multiply(T1 num1,T2 int num4=3;
num2) cout<<"\n Product of
{ num3*num4=";
cout<<num1*num2;
multiply<float,int>(num3,
}
int main()
num4);
{ cout<<endl;
int num1=3; multiply<float,float>(2.3,4
float num2=4.5; .5);
cout<<"\n Product of
num1*num2="; return 0;
multiply<int,float>(num1,num2 }
);
cout<<endl;
Overloading of function templates
template<class T>
class classname
{
//……………
//Class member specification with
//anonymous type T
//wherever appropriate.
……………
};
#include<iostream>
using namespace std; int main()
template<class T1, class {
T2>
class Test Test <float,int>
{ test1(1.23,12);
T1 a; Test <int ,char>
T2 b; test2(20, 'z');
public:
test1.show();
Test(T1 x, T2 y)
{ a=x; test2.show();
b=y; return 0;
} }
void show()
{
cout<<a<<" and "<<b<<"\
n";
}
};
Class template with inheritance(Single
level)
#include<iostream> void display()
using namespace std; {
template<class T> cout<<"a:
class alpha "<<alpha<T>::a<<endl;
{ cout<<"b: "<<b<<endl;
protected: alpha<T>::check();
T a;
}
public:
void check() };
{ int main()
cout<<"\nHello"; {
} beta<int,float> b1;
}; beta<float,int> b2;
template <class T,class T1> cout<<"\nEnter a(int) and
class beta:public alpha <T> b(float)";
{ b1.get();
private:
b1.display();
T1 b;
public: cout<<"\nEnter a(float) and
b(int)";
void get()
{ b2.get();
cin>>alpha<T>::a>>b; b2.display();
} return 0;
}
Templates with default arguments
Like function default
Output:
arguments, templates can also
have default arguments. For (Assume, char takes 1 byte and i
example, in the following takes 4 bytes)
program, the second parameter 28
U has the default value as char. Key point
Default arguments should be provide
#include<iostream> from right to left direction( if on
using namespace std; template parameter has a defau
template<class T, class U = argument, then all template paramete
char> class A following it must also have defau
{ arguments)
public: Following is not allowed as it
T x; violating the default arguments rule
U y; #include<iostream>
}; using namespace std;
int main() template<class T = char, class U, class
{ = int> class A // Error
A<char> a; {
A<int, int> b;
// members of A
cout<<sizeof(a)<<endl;
};
cout<<sizeof(b)<<endl;
int main()
return 0;
} {
Member function of class as function template(Syntax for defining member function outside of the class as function template)