File 2
File 2
CO6
Templates
Prepared by –
Dr. Soumen Moulik
Department of Computer Science & Engineering
National Institute of Technology Meghalaya
Introduction
Programmers can define a family of functions or classes that
can operate on different types of data
◦ Define the behavior of the class without specifying the datatype of
variables that will be handled by the operations of the class
◦ Fall under the category of meta-programming and auto code generation
although the generated code is never visible to the users
Act as a model of function or a class that can be used to
generate functions or classes
◦ During compilation of a program, the C++ compiler generates one or
more functions or classes based on the specified template
Widely used to implement the standard template library
(STL) to define containers, iterators, and algorithms.
◦ Containers include vectors, queues, sets, maps, hash tables, and functions
2
Function Templates
Compilers generate n copies of the code under the template function,
where n is the number of calls to the template function
The different copies are invoked with corresponding data types
Once an internal function is generated for a particular data type, all future
invocation to the template function with the same data type will refer to it
Differences between templates and macros –
Templates Macros
Code is simpler and easier to write More chances of mistakes
and understand
Easy to debug Difficult to find errors as they are
handled by pre-processor
Being a function call, they are less More efficient as they are compiled
efficient than macros inline
Performs type-checking Do not perform any type checking
3
Guidelines
Every template data type must be used in the function
declaration and/or definition
Failing to do so results in an error and will be treated as
invalid template
Template functions can also be overloaded; In such cases it will
have the same name but different argument
C++ also allows to call nested or recursive template functions
User-defined types are allowed in function templates
4
Class Templates
We can also declare classes to operate on different data types;
Such classes are called class templates
Specify how individual classes can be constructed so that they
can similar operations on different data types
Enable programmers to create abstract classes that define the
behavior of the class without actually knowing what data type
will be handled by the class operations
The process of creating a specific class from a template is
called instantiation; An instantiated object of a template class
is called a specialization
If a class template is specialized by some then it is called
partial specialization, otherwise, a full specialization
Every mem. funcn. in a class template is a function template
5
Class Templates
A function can be declared as friend inside a class template
◦ This would allow a non-member function to access the members of the
template class
◦ A template class to be a friend of a normal class
◦ An ordinary class to be a friend of a template class
◦ A template class being a friend of another template class
Can be used in conjunction with inheritance –
◦ A class can be derived from a template base class
◦ Derived class may be allowed or disallowed to have template features
◦ It is also possible to derive a non-template base class and adding some
template members to it
Can also be used with operator overloading functions
◦ We can make the class that defines operator overloaded functions a
template class
6
Pros and Cons
Advantages –
◦ A template not only enhances code reusability but also makes the code
short and easy to maintain
◦ A single template can handle different types of parameters
◦ Testing and debugging efforts are reduced
Disadvantages –
◦ Some compilers provide little support for templates
◦ Many compilers do not have clear instructions on when and how to
detect a template definition error
◦ Even when the compiler detects an error, it takes more time and effort
to debug the code and resolve the error
◦ Since a separate code is generated for each template type. Frequent use
of template can result in large executable
7
Standard Template Library
Standard Template
Containers Algorithm Iterators
Library (STL) is a
collection of classes
Sequence Retrieve Input that provide templated
containers, algorithms,
Associative Mutating Output and iterators
Programmers can use
Derived Sorting Forward them without having to
write and debug the
classes.
Set Bidirectional
The STL components
are defined in the
Relational Random
namespace std.
8
Sequence Containers
Data has a linear sequence
Each element is related to other elements by its position
along the line
Elements can be accessed using iterator
Type Description
Vector • Dynamic array that allows insertion/deletion at the end.
• Permits direct access to an element.
9
Associative Containers
Supports direct access to elements using keys
No sequential ordering of elements
Data is stored while being input, using a tree structure
Facilitates fast searching, insertion and deletion
Slow for random access, not efficient for sorting
Type Description
Set and • Store multiple data elements and provide functions to
multiset manipulate elements using their key values
• Multiset allows duplicate data, but a set does not
Map and • Stores data as pairs of key and value, while key is used for
multimap indexing and sorting, value is used to store data
• Allows manipulation of values using keys
• Multimap permits use of multiple keys for a value
10
Derived Containers
Created from sequence containers
Does not support iterators, and that is why cannot be used
for data manipulation
Support two member functions – push() and pop() for
inserting and deleting elements
Type Description
Stack • It is a Last In Fast Out (LIFO) data structure
• Insertion and deletion can be done only at one end
Priority • The first element to be taken out is the highest priority of the
queue element
11
Algorithms
Consist of functions that programmers can directly use in their
code to process data stored in different containers for processing
their data
Although each type of containers has its own set of functions to
perform basic operations, STL defines more than 60 algorithms for
extended and complex operations
STL algorithms are neither declared as member functions of any
container class nor are defined as friend functions
Can be accessed by including the header file <algorithm>
12
Iterators
Pointer-like entities that are used to access and traverse
through the elements stored in a container
Only sequence and associative containers can be used with
iterators
Type Direction Access Function Ability to
Type be saved
Input Forward Linear Read No