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

Templates in C

Templates in C++ allow the creation of functions and classes that can operate with any data type, enabling generic programming. There are two main types of templates: function templates, which allow for generic functions, and class templates, which allow for generic classes. Templates can also include multiple parameters and default arguments, making them versatile for various programming scenarios.

Uploaded by

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

Templates in C

Templates in C++ allow the creation of functions and classes that can operate with any data type, enabling generic programming. There are two main types of templates: function templates, which allow for generic functions, and class templates, which allow for generic classes. Templates can also include multiple parameters and default arguments, making them versatile for various programming scenarios.

Uploaded by

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

TEMPLATES

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

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). Note
that no automatic conversions are applied to
arguments on the template functions.
Example-Overloading of function templates
#include<iostream>
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
{
cout<<"Explicit display:"<<x<<"\n";
}
//Remaining code in next slide………….
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
Explicit display:100
Template display:56.78
Explicit display:a
Template display:5.98 b 89
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.
This will unnecessarily increase the rewriting of
same code and will be hard to maintain, as a
change is one class/function should be performed
on all classes/functions.
However, class templates make it easy to reuse
the same code for all data types.
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 are:"<<obj2.sum1();
cin>>a[i]; 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>
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)

template <class T>


returntype
classname<T>::functionname(argument_list
)
{
//……
//function body
//……
}
Example-Member function as function
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;
{
retval = a>b? a : b;
T a, b;
return retval;
public:
mypair (T first, T second) }
{ int main ()
a=first; {
b=second; mypair <int> myobject
} (100, 75);
T getmax(); 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-type parameters is, they must be const. The
compiler must know the value of non-type parameters at
compile time. Because compiler needs to create
functions/classes for a specified non-type value at
compile time.
Example: Next slide
Example-Passing nontype parameters to templates

#include <iostream> void display()


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

You might also like