0% found this document useful (0 votes)
14 views26 pages

Templates in C

Uploaded by

bhaveshtanwar693
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views26 pages

Templates in C

Uploaded by

bhaveshtanwar693
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 26

TEMPLATES

Templates
• A template is a 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)
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
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
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
{
5.6=31.36
return (num*num);
} 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);
Example 2-Function template
(WAP to display minimum of two
include<iostream> numbers)
cout<<"enter float
using namespace std; value";
template<class T> cin>>p>>q;
T min1(T a,T b) cout<<"\nmin of
integer"<<min1<int>(x,
{
y);
return(a<b?a:b);
cout<<"\nmin of floating
} value"<<min1<float>(p
int main() ,q);
{ return 0;
int x,y; }
float p,q; //Output
cout<<"enter integer Enter integer values 3 9
value"; Enter float values 1.2 3.4
cin>>x>>y; Min of integer values 3
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
template<class T> inum2="<<inum2;
void swap1(T &a, T &b) cout<<"\n fnum1="<<fnum1<<" and
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);
int main()
cout<<"\n\n After Swapping:";
{
cout<<"\n inum1="<<inum1<<" and
int inum1=4,inum2=5; inum2="<<inum2;
float cout<<"\n fnum1="<<fnum1<<" and
fnum1=4.8,fnum2=-5.3; fnum2="<<fnum2;
char c1='A',c2='a'; cout<<"\n c1= "<<c1<<" and
c2="<<c2;
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>
int num4=3;
void multiply(T1 num1,T2
num2) cout<<"\n Product of
{ num3*num4=";
cout<<num1*num2; multiply<float,int>(num3,n
} um4);
int main() cout<<endl;
{
multiply<float,float>(2.3,4.
int num1=3;
5);
float num2=4.5;
cout<<"\n Product of
return 0;
num1*num2="; }
multiply<int,float>(num1,nu
m2);
cout<<endl;
Overloading of function
templates
• A template function may be overloaded
either by a template function or ordinary
function of its name.
• Overloading resolution is accomplished as:
Compiler will first look to call an
ordinary function(or non-template
function) that has an exact match.
If ordinary function with exact match is
not present, then compiler will look to
call a template function that could be
created with an exact match.
An error is generated if no match is
found(either non-template or template).
Example-Overloading of function
#include<iostream>
templates
using namespace std;
template<class T>
void display(T x) //Function template with one generic type
{
cout<<"Template display:"<<x<<"\n";
}
template<class T1,class T2,class T3>
void display(T1 x,T2 y,T3 z) //Function template with three
generic types
{
cout<<"Template display:"<<x<<" "<<y<<"
"<<z<<"\n";
}
void display(int x)//Non-template function accepting one
integer argument
{
Example continued..
void display(char y)//Non-template function accepting one
character argument
{
cout<<"Explicit display:"<<y<<"\n";
}
int main()
{
display(100); //Calls display(non-template) which accepts one
integer argument
display(56.78);//Calls display(template) accepting one generic
type
display('a');// Calls display(non-template) which accepts one
character argument
display(5.98,'b',89);// Calls display(template) accepting three
generic types
return 0;
}
//Output
Class templates
• Like function templates, we can also
create class templates for generic class
operations
• Class templates are also known as generic
classes
• Sometimes, we need a class
implementation that is same for all
classes, only the data types used are
different.
• Normally, we would need to create a
different class for each data type /or
create different member variables and
functions within a single class.
Syntax of class template

template<class T>
class classname
{
//……………
//Class member specification with
//anonymous type T
//wherever appropriate.
……………
};

T may be substituted by any data type


including user defined data types.
Example 1-Class template
include<iostream>
int main()
using namespace std;
template <class T> {
class abc abc<int>obj(10,20);
{ cout<<"\nmax value is
T a,b; "<<obj.max1();
public: abc<float>obj1(10.2,34.7)
abc(T x,T y) ;
{
cout<<"\nmax value is
a=x;
"<<obj1.max1();
b=y;
} abc<char>obj2('A','a');
T max1() cout<<"\nmax value is
{ "<<obj2.max1();
return (a>b?a:b); }
}
};
Example 2-Class template
#include<iostream> T sum1()
using namespace std; {
template <class T> T sum=0;
class abc for(int i=0;i<size;i++)
{ sum=sum+a[i];
T *a; return sum;
int size; }
public: };
abc() int main()
{ {
cout<<"\n Enter the size of abc<int> obj1;
array:"; cout<<"\n Sum of integer
cin>>size; array elements
a=new T[size]; are:"<<obj1.sum1();
cout<<"\n Enter the array abc<float>obj2;
values:"; cout<<"\n Sum of float array
for(int i=0;i<size;i++) elements
cin>>a[i]; are:"<<obj2.sum1();
} return 0;
}
Class template with
multiple parameters
We can use more than one generic type in the class
template by using the comma to separate the list.

template <class T1, class T2,….>


class classname
{
……..
………(body of the class)
};
Example-Class template with
multiple parameters
#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> test2(20,
T2 b;
'z');
public:
Test(T1 x, T2 y) test1.show();
{ 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;
{
protected: cout<<"b: "<<b<<endl;
T a; alpha<T>::check();
public: }
void check() };
{
int main()
cout<<"\nHello";
} {
}; beta<int,float> b1;
template <class T,class T1> beta<float,int> b2;
class beta:public alpha <T> cout<<"\nEnter a(int) and
{ b(float)";
private:
b1.get();
T1 b;
public: b1.display();
void get() cout<<"\nEnter a(float) and
{ b(int)";
cin>>alpha<T>::a>>b; b2.get();
}
Templates with default arguments
• Like function default Output:
arguments, templates can (Assume, char takes 1 byte and int
also have default takes 4 bytes)
arguments. For example, in 2
the following program, the
8
second parameter U has the
Key point
default value as char.
Default arguments should be provided
from right to left direction( if one
#include<iostream> template parameter has a default
using namespace std; argument, then all template parameters
template<class T, class U = following it must also have default
char> class A arguments)
{ Following is not allowed as it is
public: violating the default arguments
T x; rule:
U y; #include<iostream>
}; using namespace std;
int main() template<class T = char, class U, class V
{ = int> class A // Error
A<char> a; {
A<int, int> b; // members of A
cout<<sizeof(a)<<endl;
Member function of class as
function template
(Syntax for defining member function
outside of the class as function template)
template <class T>
returntype
classname<T>::functionname(argument_list
)
{
//……
//function body
//……
}
template
(Defining outside of the class)
#include <iostream> template <class T>
using namespace std; T mypair<T>::getmax ()
template <class T>
{
class mypair
{ T retval;
T a, b; retval = a>b? a : b;
public: return retval;
mypair (T first, T second) }
{
int main ()
a=first;
b=second; {
} mypair <int> myobject
T getmax(); (100, 75);
}; cout <<
myobject.getmax();
return 0;
More points with respect

to templates
Difference between function overloading
and templates?
Function overloading is used when multiple
functions do similar operations, templates are
used when multiple functions do identical
operations.

 Can we pass nontype parameters to


templates?
We can pass non-type arguments to templates.
Non-type parameters are mainly used for
specifying max or min values or any other
constant value for a particular instance of a
template. The important thing to note about non-
Example-Passing nontype parameters to templates

#include <iostream> void display()


using namespace std; {
template<class T, int size>
class A
for(int
{ i=0;i<size;i++)
public: {
T arr[size]; cout << arr[i]
void insert1() << " ";
{
int i =1;
}
for (int j=0;j<size;j++) }
{ };
arr[j] = i; int main()
i++; {
}
}
A<int,10> t1;
t1.insert1();
t1.display();
return 0;

You might also like