0% found this document useful (0 votes)
38 views17 pages

C++ Template Programming Concepts

Uploaded by

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

C++ Template Programming Concepts

Uploaded by

manan grover
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

12

Templates

Key Concepts 12.1 Introduction

Generic programming Templates is one of the features added to


C++ recently. It is a new concept which
Multiple parameters in class enable us to define generic classes and
templates functions and thus provides support for
Function templates generic programming. Generic programming
Template functions isan approach where generic types are used
as parameters in algorithms so that they
Member function templates work for a variety of suitable data types
Class templates and data structures.
Template classes
Atemplate can be used to create a family
Multiple parameters in class of classes or functions. For example, a class
templates template for an array class would enable
Overloading of template functions us to create arrays of various data types
Non-type template arguments such as int array and float array.
Similarly, we can define a template for a
function, say mul(0, that would help us create various versions of mul() for multiplying int,
loat and double type values.
Atemplate can be considered as a kind of macro. When an object of a specific tyvpe is
defined for actual use,the template definition for that class is substituted with the required
tata type. Since a template is defined with aparameter that would be replaced by a specified
data type at the time of actual use of the class or function, the templates are sometimes
edparameterized classes or functions.
360 Object-Oriented Programming with C++

12.2 Class Templates


Consider a vector class defined as follows:

class vector
{
int *V;
int size;
public:
vector(int m) // create a null vector

V= new int[size = m];


for(int i=0; i<size; i++)
v[i] = 0;
vector(int *a) // create a vector from an array

for (int i=0; i<size; i++)


v[i] = a[i]:
int operator* (yector &y) // scalar product

int sum = 0;
for(tnt i-0; i<size; i++).
súm += this -> v[j] * y . v[i];
return sum;

Thevector class can store an array of int


numbersand perform the scalar product of two
int vectors as shown below:

int main()

int x[3] = (1,2, 3);


int y[3] =(4,5,6);. // Creates a null vector of 3 integers
veotor v1(3);
vector 2(3)>» // Creates vl from the array x
v1 = X;
v2 = y;
int R = v1 * v2:
<< R:
Cout << "R = !
return 0; R.
}
361
Templates
array of float values. We can
Now suppose we want to define a vector that can store an vector class.
float in the
do this by simply replacing the appropriate int declarations with
This means that we have to redefine the entire class all over again.

a parameter and then


Assume that we want to define a vector class with the data type as
of defining a new class every time.
use this class tO create avector of any data type instead
The template mechanism enables us to achieve this goal.
classes. It is a simple process
As mentioned earlier, templates allow us to define generic
an anonymous type. The general format of a
to create a generic clas using a template with
class template is:

template<cl ass T>


class classname

// class member specification


// with anonymous type T
/ wherever appropriate

shown below illustrates the syntax of a template:


The temnplate definition of vector class
template<class T>
class vector

T* V; // Type T vector
int size;
public:
vector(int m)
= m:
V = new T sizei<size;
for(int i=0; it+)
v[i] =0;
vector (T* a)
for(int i=0; i<size, i+)
v[i] = a[i];

(vector &y)
T operator*
T sum = 0;
for(int i=0; i<size; i++) v[i]:
sum += this -> v[i] * y.
return sum;
362

note
The lnn (omplate definition ia vory amilar to an orinaryclass tefinti en.the

hnl m aparameterized clann witlh the type '" anitsparnneter Tmnyla satetitass
liftoreit data (ypon
Nxample
vector int vI(10): /| 10 element int vec tor
vector loat v2(25): 1/ 29 e lement flout veclor
note
"The type T may reprenenl a clasn name as well, Kxnmple:
vector <complex- v3(5): // vector of 5 comp lex numbers

Aclans eronted trom aclars tomplate in enlled atemplate rlunn, The nyntax fhur defining, a.
objeet of a template clasn in:

classname<type> objectname (argl ist):


This process of erenting a specific clas from acass ternplatein called instantiatin, Th:
compiler will perform the error nnalysin only when an instantiation takes plats. It. is,
therefore, advisable to ereate and debug an ordinary class before onverting it into a t:nplat:
Progranms 12.Iand 12.2 ilustrate the use ofa vector class tenplate fur pe:rforrning the
scalar product of int type vectors as well as float type vectors.
Example of Class Template
#include <iostre am
using namespace std;

const size = 3;

template <class T>


class vector

T* V; 1/ type T vector
public:
vector()

Contdy
Template "363

vnew T[size) :
for (int i-0;1<size;i**))
v[1] 0;
vector(T* a)

for(int i0;1<s1ze; i++)


v[1] a[i) :
Toperator" (vector &y)
T sum 0;
for (int i-0;i<size;itt)
sum * this - v[i) *y.v[i]:
return sum;

int main()

int x[3] - (1,2,3}:


int y[3) (4,5,6):
véctor <int> vl;
vector <int> v2:
vl = x;
v2 yi
int R Vl * v2;
cout << "R " <<R << "\n:
return 0;
PROGRAM 12.1

would be:
Theoutput of the Program 12.1
R 32

ANOTHER EXAMPLE OF CLASS TEMPLATE


include <iostream>

using namespace std;

const size 3;
(Contd)
templ ate <class T>
364 Object-Oriented Programming with C++

class vector
{
T* V; 1/ type T vector
public:
vector()

V =new T[size] ;
for(int i=0;i<size;i++)
v[i] =0;
vector (T* 'a)
{
for(int i-0;i<size;i++)
v[i] a1]:
Toperator* (vector &y)
Tsum = 0;
for (int i =0; i<size;i++)
sum + this -> v[1] * y.v[i]:
return sum;

int main ()

float x[3) (1.1,2.2,3.3) ;


float y[3] (4.4,5.5,6.6) ;
vector <float> vl;
vector <float> v2;
v1 = X;
v2 = y;
float R = vl * v2;
cout < "R <<R << "\n":

return, 0;

PROGRAM 12.2

The output of the Program 12.2 would be:


R= 38. 720001
365
Templates

12.3 Class Templates with Multiple Parameters


We can use more than one generic data type in a class template. They are declarcd as a
comma-separated list within the template spccification as shown below:
template<class T1, class T2, ..>
class classname

(Body of the class)

Program 12.3 demonstrates the use of a template class with two generic data types.
THO GENERIC DATATYPES TN ACEAS DEFINITION
#include <iostream>

using namespace std;


template<class T1, class T2>
class Test

T1 a;
T2 b;
public:
Test (T1 X, T2 y)
å = X;
b = y;

void show()
COut << a <<" and << b << "\n":

int main()
{
Test <float, int> testl (1.23,123);
Test <int,char> test2 (100, 'W');
testl.show();
test2.show();

return 0;

PROGRAM 12.3
366 Object Oriented Programming with C++
The output of Program 12.3 will be would be:
1.23 and 123
100 and W

12.4 Function Templates


Like class templates, we can also define
family of functions with different angumentfunction templates that could be used to create a
types. The general format of a fünction template is:
templ ate<class T>
returntype functioname (arguments of type T)

1/ Body of function
|/ with type T
|/ wherever appropriate
||.....
The function template syntax is similar to that of the
class template except that we are
defining functions instead of classes. We must use the template
necessary in the function body and in its argument list. parameter T as and when
The following example declares a swap() function
a given type of data. template that will swap two values of
templ ate<class T>
void swap (T&x, T&y)
T temp = X;
X = y;
y = temp;

This essentially declares a set of overloaded functions, one for


invoke the swap() function like any ordinary function. For each type of data. We can
swap) function as follows: example, we can apply the
void f(int m,int n,float a,float b)
Swap (m,n); |/Swap two integer values
Swap(a,b) ; // swap two float values
Templates "367

This willgenerate a swap) function from the function template for each set of argument
types. Program 12.4 shows how a template function is defined and implemented.
FUNCTION TEMPLATE AN EXAMPLE
#include <iostream>

using namespace std;

template <class T>


void swap (T &x, T&y)
Ttemp= X;
X= y;
y = temp;

void fun (int m, int n,float a,fl oat b)


cout << "m and n before swap: <<m <e << n << "\n":
Swap (m,n); <<m << <<n <« "\n
cout cK "m and n after swap:
<<b << "\n":
cout << "a and b before swap:" << a <<
swap(a,b): << a << # <«b << "\n":
cout << "a and b after swap:

int main()

fun (100, 200,11 .22,33.44);


return 0;
PROGRAM 12.4

The output of Program 12.4 would be:


m andn before swap: 100 200
m and n after Swap: 200 100
11.22 33.439999
a and b before swap:
33.439999 11.22
a and b after Swap:

Another function often used is sort) for sorting arrays of various types such as int and
bubble sort:
double.The following example shows a function template for
368 Object Oriented Programming with C+*
templ ate<class T>
bubble(1 v). int n)
for (int i-0; i<n-l; f*+)
for(int i-n-l:i: -)
1f (v[j] < v[3-1])
Ttemp v[3]:
v[3] v[j-1):
v[j-1] temp:

Notethat the swapping statements


T temp v[jl:
v[j] v[j-1]:
v[j-1] - temp;
may be replaced by the statement

swap(v[3),v[j-1]):
where swap() has been defined as a function template.
Here is another example where a function returns a value.
templ ate<cl ass T>
T max (T x, Ty)

return X>y ? x:y;

A function generated from a function template is called a template function.


demonstrates the use of two template functions in nested form for implementing Program 12.5
sort algorithm. Program 12 6shows another example of the bubble
application of template functions
BUBSLE SOSTNTOIPATE
#include <105tream>
using namespace std;

templ atecclass I>


vo1d bubble(T aD, int n)
Contd
Templates 369

for (int i=0; i<n-l; it+)


for(int j=n-1; i<j; j--)
if(a[j] <a[j-1])
swap(a[j] , a[j-1]) ; // calls template function

templ ate<class X>


void swap (X &a, X &b)
{
X temp = a;
a = b;
b= temp;

int main()
{
int x[5] = (10,50, 30,40, 20}:
float y[5] = (1.1,5.5,3.3,4.4,2.2) ;
bubble(x,5) ; // calls template function for int values
bubble(y,5) ; // calls template function for float values
cout << "Sorted x-array : 9

for (int i=0; i<5; it+)


cout << x[i] <<
cout << endl;

cout << "Sorted y-array:


for (int j=0; j<5; j++)
cout << y[il << " ":
cout << endl;

return 0;

PROGRAM 12.5

The output of Program 12.5 would be:

Sorted x-array: 10 20 30 40 50
Sorted y-array: 1.1 2.2 3.3 4.4 5.5
370 ObjetOiented Programming wth C
AN APPLICATION OF TEMPLATE FUNCTION
#include iostream
include iomanip
#include cmath
sing namespte s1d:

template lass 1
void roots(1 a, b,1 )
Id b*b 4atci
if(d 0) 1/ Roots are equal
" - b / (2*a) << endl;
else if(d 0) 1/ Two real roots

Cout << "Roots are real \n":


tloat R- sqrt(d);
fioat RI (-b+R)/(2*a) :
float R2 (-b-R)/(2*a):
Cout <K "R1 * " << RI <«" and ":
Cout << "R2 " << R2 << endl:

else |/ Roots are complex

cout "Roots are complex \n";


float R1-b/(2 *a):
float R2 sqrt(-d)/(2*a);
Cout << "Real part " << R1 << endl;
Cout < "Imaginary part " c< R2;
cout << endl;

int main)
cout << "Integer coefficients \n";
roots(0,-5,6);
Cout < "\nfloat coefficients \n":
root0.5,3.6,5.0):

PROGRAM 12.6
371
Templates
bc:
The output of Program 12.6 would
Integer coefficients
Roots are real

R1 = 3 and R2 = 2
Float coefficients
Roots are complex
Real part = -1.2
Imaginary part = 1.375985

Multiple Parameters
12.5 Function Templates with
statement,
generic data type in the template
template classes, we can use more than one
Like list as shown below:
using a comma-separated
template<class TI, class T2, ..>
functionname (arguments of types T1, T2,..)
returntype

(Body of function)

template functions.
two generic types in
Program 12.7 illustrates the concept of using
GENERIC TYPES
FUNCTION WITH THO
#include <iostream>
#include <string>

using namespace std;

T2>
template<class T1, class
y)
void displ ay (T1 x, T2
"\n";
COut << X <<
" " << y <<

int main ()
"EBG") ;
display(1999, ;
display(12.34, 1234)
return 0; PROGRAM 12.7
372 Object-Oriented Programming with C++
The output of Program 12.7 would be:
1999 EBG
12.34 1234

12.6 Overloading of Template Functions


Atemplate function may be overloaded either by template functions or ordinary functions
of its name. In such cases, the overloading resolution is accomplished as follows:
1. Call an ordinary function that has an exact match.
2. Call a template function that could be created with an exact match.
3. Try normal overloading resolution to ordinary functions and call the one that matches.
An error is generated ifno match is found. Note that no automatic conversions are applied
to arguments on the template functions. Program 12.8 shows how a temnplate function is
overloaded with an explicit function.

TEMPLATE FUNCTION WITH EXPLICIT FUNCTOC


#include <iostream>
#include <string>

using namespace std;

template <class T>


void display (T x)
cout << "Template display: << X << "\n";
void displ ay (int x) 1/ overloads the generic disploy ()
{
cout << "Explicit display: " << X << "\n";

int main()

display(100);
display (12.34);
displ ay ('C');
return 0;

PROGRAM 12.8
-373
Templates

The output of Program 12.8 would be:


Explicit display: 100
Templ ate display: 12.34
Templ ate display: C
note
display ) and not the template
The call display(100) invokes the ordinary version of
version.

12.7 Member Function Templates


template for vector, all the member functions were defined as
When we created a class as well. But
was not necessary. We could have defined them outside the class
inline which template classes themselves are parameterized
remember that the memnber functions of the and therefore these functions must be
their template classes)
by the type argument (to the following general form:
defined by the function templates. It takes
Template<class T>
onname(arglist)
returntype classname <[> :: functi

// Function body

template and its member functions are redefined as follows:


The vector class
/ Class template

templ ate<class T>


class vector

T* V;
int size;
pubiic:
vectur(int m);
vector(T* a);
(vector & y);
T operator*

templates
1/ Member function
template<class T>
Object-Oriented Programming with Ct+
374 -
vector< > :: vector(int m)

V new T[size = m]:


for(int i=0; i<size; i++)
v[i] = 0;
}

template< class T>


vector<T> :: vector (T* a)

for(int i=0; i<size; it+)


v[i] = a[i];

template< class T>


T vector<T> :: operator* (vector & y)

T sum = 0;
for(int i = 0; i <size; it+)
sum += this -> v[i] * y.v[il;
return sum;

12.8 Non-Type Template Arguments


We have seen that a template can have
type arguments. That is, in addition to themnultiple
type
arguments. It is also possible to se non
such as strings, function names, constant argument T, we can also use other arguments
following example: expressions and built-in types. Consider tne
template<class T, int size>
class array
T a[size]: |/ automatic array
initial izgtion

This template supplies the size of the


the array is known to the array as an argument. This that the sizebo
specified whenever a templatecompiler at the compile time itself. implies must
class created. Example:
is The arguments
array<int,10> al; | Array of 10
array<float , 5> a2; || Array of 5 integers
array<char,20> a3; |/ String of sizefloats
The size is given as an 20
argument to the template class.
375
Templates

SUMMARY

mechanism known as template to implement the concept of generic


C++ supports a
programming.
generate a family of classes or a family of functions to handle
Templates allows us to
different data types.
functions eliminate code duplication for different types and thus
Template classes and
and more manageable.
make the program development easier templates.
parameters in both the class templates and function
We can use multiple template class and the process
class template is called a
Aspecific class created from a as instantiation. Similarly, a specific function
is known
of creating a template class called a template function.
created from a function template is
functions can be overloaded.
Like other functions, template defined as function templates using
the
template must be
Member functions of aclass
parameters of the class template. types as arguments
parameters such basic or derived data
non-type
> We may also use
templates.

Key Terms
parameterized classes
bubble sort parameterized functions
class template swapping
display () swap()
explicit function template
function template template class
generic programming template definition
instantiation template function
member function template template parameter
multiple parameters template specification
overloading templates
parameter

You might also like