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

Templates in C++

Templates allow functions and classes to be reused with different data types. Templates are a powerful feature of C++ that enables generic programming. There are two types of templates in C++: class templates (also called generic classes) and function templates (also called generic functions). Templates avoid code repetition by allowing a single function or class to work with multiple data types.
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)
174 views26 pages

Templates in C++

Templates allow functions and classes to be reused with different data types. Templates are a powerful feature of C++ that enables generic programming. There are two types of templates in C++: class templates (also called generic classes) and function templates (also called generic functions). Templates avoid code repetition by allowing a single function or class to work with multiple data types.
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)
– Function template(or Generic functions)
• Advantage  avoid repetition of source code.
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 5.6=31.36
{
return (num*num); Square of 123.456=15241.4
}
int main()
{
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);
} return 0;
int main() }
{ //Output
int x,y; Enter integer values 3 9
float p,q; Enter float values 1.2 3.4
cout<<"enter integer 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 fnum2="<<fnum2;
void swap1(T &a, T &b) cout<<"\n c1= "<<c1<<" and c2="<<c2;
{ swap1<int>(inum1,inum2);
T temp=a; swap1<float>(fnum1,fnum2);
a=b; swap1<char>(c1,c2);
b=temp; cout<<"\n\n After Swapping:";
} cout<<"\n inum1="<<inum1<<" and inum2="<<inum2;
int main() cout<<"\n fnum1="<<fnum1<<" and fnum2="<<fnum2;
{ cout<<"\n c1= "<<c1<<" and c2="<<c2;
int inum1=4,inum2=5; return 0;
float fnum1=4.8,fnum2=-5.3; }
char c1='A',c2='a';
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 : ";
{
read<int>(Array);
Type Total = 0;
cout<<"\n Sum of elements =
for(int i=0;i<MAX;i++)
"<<sum<int>(Array);
Total += A[i];
cout<<"\n Enter the float array elements : ";
return Total;
read<float>(Array1);
}
cout<<"\n Sum of elements =
template<class Type>
"<<sum<float>(Array1);
void read(Type A[])
}
{
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,num4);
} cout<<endl;
int main() multiply<float,float>(2.3,4.5);
{
return 0;
int num1=3;
float num2=4.5; }
cout<<"\n Product of num1*num2=";
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>
using namespace std;
int main()
template <class T> {
class abc abc<int>obj(10,20);
{ cout<<"\nmax value is "<<obj.max1();
T a,b;
abc<float>obj1(10.2,34.7);
public:
abc(T x,T y) cout<<"\nmax value is "<<obj1.max1();
{ abc<char>obj2('A','a');
a=x; cout<<"\nmax value is "<<obj2.max1();
b=y;
}
}
T 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 array:"; abc<int> obj1;
cin>>size; cout<<"\n Sum of integer array elements
a=new T[size]; are:"<<obj1.sum1();
abc<float>obj2;
cout<<"\n Enter the array values:";
cout<<"\n Sum of float array elements
for(int i=0;i<size;i++)
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> test2(20, 'z');
T2 b; test1.show();
public: test2.show();
Test(T1 x, T2 y) return 0;
{ a=x;
}
b=y;
}
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: "<<alpha<T>::a<<endl;
class alpha
{ 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 b(float)";
class beta:public alpha <T>
{ b1.get();
private: b1.display();
T1 b; cout<<"\nEnter a(float) and b(int)";
public: b2.get();
void get()
b2.display();
{
cin>>alpha<T>::a>>b; return 0;
} }
Templates with default arguments
• Like function default arguments, templates Output:
can also have default arguments. For (Assume, char takes 1 byte and int takes 4 bytes)
example, in the following program, the 2
second parameter U has the default value as
char.
8
Key point
Default arguments should be provided from right to left
#include<iostream>
direction( if one template parameter has a default argument,
using namespace std;
then all template parameters following it must also have default
template<class T, class U = char> class A
arguments)
{
Following is not allowed as it is violating the default
public:
T x;
arguments 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; // members of A
A<int, int> b; };
cout<<sizeof(a)<<endl; int main()
cout<<sizeof(b)<<endl; {
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;
{
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 (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 i=0;i<size;i++)
class A
{
{
public: cout << arr[i] << " ";
T arr[size]; }
void insert1() }
{ };
int i =1; int main()
for (int j=0;j<size;j++)
{
{
arr[j] = i; A<int,10> t1;
i++; t1.insert1();
} t1.display();
} return 0;
}

You might also like