Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 35

C++ Templates

Templates
Templates is one of the features added to c++ recently.
It is a new concept which enable us to define generic
classes and functions and provides support for generic
programming.
Generic programming 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.

Templates
A template can be used to create a family of classes or

functions.
For example, a class template for an array class would enable

us to create arrays of various data types such as int array and


float array.
Similarly we can define a template for a function say mul,

that would help us create various versions of mul() for


multiplying int, float and double type values.

Template
A template can be considered as a kind of macro.
When an object of a specific type is defined for actual use,

the template definition for that class is substituted with the


required data type.
Since n template is defined with a parameter that would be

replaced by a specified data type at the time of actual use of


the class or function, the templates are sometimes called
parameterized classes or functions.

Templates
Type-independent patterns that can work with multiple data types.
Generic programming
Code reusable

Function Templates
These define logic behind the algorithms that work for multiple data types.

Class Templates
These define generic class patterns into which specific data types can be
plugged in to produce new classes.

Templates
Templates
Easily create a large range of related functions or classes
Stencils out of which we trace shapes.
Function template
e.g. We might write single function template for an array-sort
function, then have C++ generate separate function-template
specializations that will sort int arrays, float arrays, string arrays
and so on.
- Class Templatee.g. We might write a single class template for a stack class, then have
C++ generate separate class-template specializations such as a
stack-of-int class, a stack-of-float class, a stack-of-string class and
so on.

Function Templates

Function Templates
Function templates are used to create a family
of functions with different type arguments .
General format of a function template

Function and function templates


C++ routines work on specific types. We
often need to write different routines to
perform the same operation on different data
types.
int maximum(int a, int b, int c)
{
int max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
}

Function and function templates


float maximum(float a, float b, float c)
{
float max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
}

Function and function templates


double maximum(double a, double b, double c)
{
double max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
}

The logic is exactly the same, but the data type is different.
Function templates allow the logic to be written once and
used for all data types generic function.

Function Templates
All function template begins with keyword template followed

by a list of template parameters to the function template


enclosed in angle brackets (< and >)
Each template parameter that represents a type must be

preceded by either of the keywords class or typename


template <typename T>
template <class ElementType>
Keywords typename and class used to specify function

template parameters actually mean any fundamental type or


user-defined type.

Function Templates
Generic function to find a maximum value
(see maximum example).
Template <typename T>
T maximum(T a, T b, T c)
{
T max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
}
Template function itself is incomplete because the compiler will need
to know the actual type to generate code. So template program are
often placed in .h to be included in program that uses the function.
C++ compiler will then generate the real function based on the use of
the function template.

Function Templates Usage


After a function template is included (or defined), the function can
be used by passing parameters of real types.
Template <typename T>
T maximum(T a, T b, T c)

int i1, i2, i3;

int m = maximum(i1, i2, i3);


maximum(i1, i2, i3) will invoke the template function with
T==int. The function returns a value of int type.

Function Templates Usage


Each call to maximum() on a different data type forces the
compiler to generate a different function using the template.
int i1, i2, i3;
// invoke int version of maximum
cout << "The maximum integer value is: "
<< maximum( i1, i2, i3 );
// demonstrate maximum with double values
double d1, d2, d3;
// invoke double version of maximum
cout << "The maximum double value is: "
<< maximum( d1, d2, d3 );

Another example
template< typename T >
void printArray( const T *array, int count )
{
for ( int i = 0; i < count; i++ )
cout << array[ i ] << " "; cout << endl;
}

Usage
int main()
{
int aCount =5; // size of array a
int bCount =7; // size of array b
int cCount =6; // size of array c
int a[aCount] ={1,2,3,4,5};
double b[bCount] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7};
char c[cCount] = HELLO;

printArray(a, aCount);
printArray(b, bCount);
printArray(c, cCount);
}

Usage
template< class T >
void printArray( const T *array, const int count );
char cc[100];
int
ii[100];
double dd[100];
myclass xx[100]; <- user defined type can also be used.

printArray(cc, 100);
printArray(ii, 100);
printArray(dd, 100);
printArray(xx, 100);

Use of template function


Can any user defined type be used with a template
function?
Not always, only the ones that support all operations used
in the function.
E.g. if myclass does not have overloaded << operator, the
printarray template function will not work.
If a template is invoked with a user-defined type, and if
that template uses functions or operators (e.g., ==, +, <=)
with objects of that class type, then those functions and
operators must be overloaded for the user-defined type.
Forgetting to overload such operators causes compilation
errors.

Use of template function


In this example, the template mechanism saves
the programmer from having to write three
separate overloaded functions with prototypes
void printArray( const int *, int );
void printArray( const double *, int );
void printArray( const char *, int );
that all use the same code, except for type T

Class Template

Syntax

Class template
So far the classes that we define use fix data types.
Sometime is useful to allow storage in a class for
different data types.
Example: simplelist1 (a list of int type elements)
example
What if we want to make a simple list of double type?
Copy paste the whole file and replace int with double

Class template
Function templates allow writing generic
functions that work on many types.
Same idea applies to defining generic classes
that work with many types -- extract the type
to be a template to make a generic classes.

Class Templates
Class templates
Allow type-specific versions of generic classes

Format:
template <class T>
class ClassName{
definition
}

Need not use "T", any identifier will work


To create an object of the class, type
ClassName< type > myObject;
Example: Stack< double > doubleStack;

Class Templates
Template class functions
Declared normally, but preceded by template<class T>
Generic data in class listed as type T
Binary scope resolution operator used
Template class function definition:
template<class T>
MyClass< T >::MyClass(int size)
{
myArray = new T[size];
}
Constructor definition - creates an array of type T

Output

Enter two integers: 10 20


20 is larger.
Enter two floating-point numbers: 10.5 20.5
20.5 is larger.
Enter two characters: r t
T has larger ASCII value.

STL
Templates can be used to create generic classes and functions
that can be extended to support generic programming.
Alexander Stepanov and Meng Lee developed a set of general
purpose templatized classes and functions that can be used for
storing and processing of data . The collection of these generic
functions and classes is called STL.
Using STL, one can save considerable time and effort and
write high quality programs because we are reusing the well
written and well tested components defined in the STL .

Standard Template Library


STL components are now part of standard C++
library are defined in the namespace std.
We must therefore use the using namespace
directive
Using namespace std

Components of Standard Template Library


The STL contains several components. But at
its core are three key components. They are:
Containers
Algorithms
Iterators

Components

Components
Container:
A container is an object that actually stores data.
It is a way data is organized in memory. The STL containers are implemented by

template classes and therefore can be easily customized to hold different types
of data.

Algorithm:
It is a procedure that is used to process the data contained in the containers.
The STL includes many different kinds of algorithms to provide support to tasks

such as initializing, searching, copying , sorting and merging.


They are implemented by template functions.

Components
Iterator:
It is an object (like a pointer) that points to an element in a
container.
We can use iterators to move through the contents of
containers.
They are handled just like pointers.
They connect algorithms with containers and play a key role
in the manipulation of data stored in the containers.

You might also like