0% found this document useful (0 votes)
13 views32 pages

Chapter 5 - Templates 2

Chapter 5 discusses templates and generic programming in C++, highlighting their ability to create algorithms that work with any data type, thus promoting code reusability and type safety. It covers the classification of templates into function and class templates, as well as the Standard Template Library (STL) which provides optimized data structures and algorithms. The chapter also includes examples and practice questions to illustrate the practical application of templates.

Uploaded by

tereshabhatt
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)
13 views32 pages

Chapter 5 - Templates 2

Chapter 5 discusses templates and generic programming in C++, highlighting their ability to create algorithms that work with any data type, thus promoting code reusability and type safety. It covers the classification of templates into function and class templates, as well as the Standard Template Library (STL) which provides optimized data structures and algorithms. The chapter also includes examples and practice questions to illustrate the practical application of templates.

Uploaded by

tereshabhatt
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
You are on page 1/ 32

Chapter 5

Templates and Generic


Programming

Compiled by Sabin Thapa


Introduction to template and generic programming
• Generic programming enables the programmer to write a general
algorithm which will work with all data types.
• It eliminates the need to create different algorithm for each and every data
types (integer, string etc.)
• Templates are the foundations of generic programming, which involves
writing code in such a way that it is independent of any datatype.
• A template is a blueprint or formula for creating a generic class or function.
• The simple idea is to pass datatype as parameter so that we don’t need to
write the same code for different data types.
• For example, we need a sort() function for different data types. So, rather
than writing many sort() function for each and every datatype, we can
write one sort() function and pass datatype as an argument.
Introduction to template and generic programming
• Templates are powerful features of C++ which allows
us to write generic programs.
• Templates allow programmer to create a common
class or function that can be used for a variety of data
types.
• The parameters used during its definition are of
generic type and can be replaced later by actual
parameters.
• Since a template is defined with a parameter that
would be replaced by a specific data type at the time
of actual use of the class or function, the template is
also called as parameterized class or functions.
Features / Advantages of Template
1. Type Safety
• Templates are type safe. Because the type that templates act upon are
known at compile time, the compiler can perform type checking before
error occurs.
2. Reusability
• We use templates in situation that results in duplication of same code for
multiple types. For eg: we can use function templates to create a set of
functions that apply the same algorithm to different data types.
3. Performance
• Defining and using templates are a compile time mechanism. Because of
this, there is no runtime overhead associated with using them.
Classification of Templates
• There are two types of templates
a) Function Templates
b) Class Templates
Function Template (Generic Function)
• Normally, if we need to perform
identical operations on two or more
types of data, we use function
overloading (as shown in figure) to
create two functions with the
required function declaration.
• However, a better approach would
be to use function templates.
Function Template (Generic Function)
• When a single function is written for a family of similar functions, then it is called a
Function template.
• The function template does not specify the actual data types of the argument that a
function accepts but it uses a generic or parameterized data types.
• Syntax: Note:
• While declaring template we can
use either keyword class or
typename.
• Similarly, the return type of
function can be the template_name
(Here, T), void or any other data
types.
• Example: • For simplicity,
or • Use template_name (if you
want same datatype that is
being passed as parameters)
• Use void, (if you have no
return statement in function)
• Use int, float or any other
return types (if you want to
return specific datatype)
Function Template: Sample Program 1
WAP using function template to accept two integers, two floating numbers and two
strings, and then add them.
Method 1:

• Note:
• While passing numbers and character, compiler automatically identifies datatype
so no need to declare the data type as shown in line 10 and 11.
• While passing string we need to declare the data type as shown in line 13
Function Template: Sample Program 1
WAP using function template to accept two integers, two floating numbers and two
strings, and then add them.
Method 2:

• Note:
• We can also declare the specific data type that the function template can
accept while calling the function template.
Function Template: Sample Program 2
WAP using function template to
accept two integers, two floating
numbers and two characters, and
then display the largest among
them.
Function Template: Sample Program 3
WAP using function template to accept two
integers, two floating numbers and two characters,
and then swap them.
• Note:
• During swapping, we often use pass by reference to the
call the function.
• If the use pass by value to call the function, then the
copies of the variable will be created within the function
thus any change made to variable inside the function
will not be observed on the original variable.
• Thus, here reference pointer of variables, i1, i2, f1, f2 c2
and c2 are passed to the function swap_places().
Practice Questions
1. WAP using function template,
• to accept two integers and display the sum and average, and
• also two floating numbers and display the sum and average.
2. Write a function template to calculate the sum and average of numbers.
same as above 2009 Fall
Practice Questions Solution
Write a function template to calculate the sum and average of numbers.
Solution: 2009 Fall

Note:
• You must declare separate template for each function template being overloaded even if the function uses
the same template name in both functions
• Here, line 4 and line 10 declare template with same template name T, but it should be declared for both
functions even if the template name T is same for both functions
Class Template (Generic Class)
• When a single class is written for a family of similar class then it is
called class template.
• C++ offers the ability to create class that contains one or more data
types that are generic or parameterized.
• The process of declaring the class template is same as that of function
template.
Class Template (Generic Class)
• Syntax: • Example:
Class Template: Sample Program 1
WAP using class template to initialize two
integers and two floating numbers at
compile time via object creation and then
display the sum.
Class Template: Sample Program 2
WAP using class template to accept two integers and
two floating numbers from user and then display the
sum.
Class Template: Sample Program 3
Create a template class to find the scalar product of vectors of integers and vectors of floating-point numbers.
Scalar product Formula:
Overloading of Function Template
• A template function also supports the overloading mechanism like as the
normal functions.
• In such cases. the compiler observes the following overloading resolution
rules for choosing an appropriate function:
1. Call normal 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 normal function and call the one
that matches
• In case no match is found, an error will be reported. Note that no automatic
(implicit) conversion are applied to parameters of template function.
Overloading of Function Template
Sample Program 1: WAP to show that normal function is prioritized over function templates in
case of overloading.

Note:
• When two floating point values are passed , then max_num() function temp[late
is called since there is no normal function that takes floating point numbers as
argument.
• When two integer values are passed , then max_num() normal function is called
since there is a normal function that takes integer numbers as argument i.e.,
normal function is prioritized over function template.
Overloading of Function Template
Sample Program 2: WAP to illustrate overloading of function templates.

Note:
• You must declare separate template for each function template being
overloaded even if the function uses the same template name in both
functions
• Here, line 4 and line 17 declare template with same template name T, but
it should be declared for both functions even if the template name T is
same for both functions
Function Template with Multiple Parameters Types
• We can also define function templates that accept more than one type
parameter, simply by specifying more template parameters between the angle
brackets.
• Example:

• Here, T1 and T2 are two template, so we can pass two different datatypes in the
parameters of this function.
Function Template with Multiple Parameters Types
WAP using function template to accept one integers and floating numbers
as parameters, then add them. The result should be the in the form of
datatype of first parameter.
Class Template with Multiple Parameters Types
• We can also class templates with more than one generic data types.
• They are declared as comma separated list in the template specification.
• Its general format is
Class Template with Multiple Parameters Types
Sample Program: WAP to illustrate the case of multiple parameters (i.e. different datatypes) in class
template.
Non-Type Template Arguments
• As we know template can have multiple type arguments. It is also possible to
use non-type arguments.
• That is, in addition to the type argument (let’s say T), we can also use other
arguments such as built-in types (such as int, float etc.), constant expression,
function name and strings.
Example:
In this example, template has two
argument one T type and other is built-
in type (int).

obj1 is an array of 30 integers.


obj2 is an array of 20 integers.
Non-Type Template Arguments
Sample Program: Class template with non-type template arguments.
Non-Type Template Arguments
Sample Program: Function template with non-type template arguments.
Standard Template Library (STL)
• In C++ Standard Template Library (STL), is a set of C++ template classes that provides general
purpose class and functions templates that can be used to implement various algorithms and
data structure such as vectors, lists, queues and stacks.
• At the core of C++ STL are following three well-structured components
1. Containers
• A containers is an object that actually stores data. STL provides various types of
containers such as vector, list, queue, map and so on. Containers are implemented by
template classes and procedure that is used to process data type.
2. Algorithms
• Algorithms act on containers. An algorithm is a procedure used to process the data
contained in the container. Some of the algorithm available in STL are initialization,
sorting, searching, merging and so on. Algorithms are implemented by template
functions.
3. Iterators
• An Iterator is an object (like pointer) that points to an element in a container. We use
iterator to move through the contents of containers. It is handled just like pointers and
can be incremented and decremented . Iterator connect algorithm with containers and
play a key role in the manipulation of data stored in the containers.
Standard Template Library (STL)
Advantages of STL
1. Efficient Data Handling
• STL provides ready-made data structures (like vector, list, map) that are highly optimized. It is
not necessary to reinvent the wheel — just use the container that best fits your problem.
2. Faster Development
• STL offers built-in algorithms (like sort, find, for_each) that save time and reduce code
complexity.
3. Generic Programming
• STL uses templates, so containers and algorithms can work with any data type (int, float,
struct, class).
4. Code Reusability and maintainability
• Code becomes modular — easy to understand, debug, and reuse.
• Reduces bugs because STL components are well-tested.
5. Performance
• STL is part of the standard library and is often optimized at the compiler level for high performance.
Standard Template Library (STL)
WAP to illustrate the use of list template to insert data into list and display them in sorted order.

• Here, list<string> is a container that can hold


elements of type string. Usually, when list
template is used a data structure, doubly
linked list is created
• push_back() is used to add elements to the
container.
• Here, sort() is a member function that sort
the list according to ascending order. So,
sort() acts as an algorithm to sort string in
ascending order.
• Here, iterators such a front() and pop_front()
are used.
• lst.front() access the first element
• lst.pop_front() removes the first element.
Standard Template Library (STL)
WAP to use vector template and its member functions to store integers.
• Here, vector<int> is a container that can hold the
elements of type int.
• Nums is the name of the vector inatane to store integers.
• push_back() is used to add elements to the container.
• Iterators are like pointer that allow algorithms to traverse
containers.
• nums.begin() points an iterator to the first element in the
vector
• nums.end() points to the position just after the last
element
• These iterators define the range over which the algorithm
operates
• Here, for_each() is an STL algorithm. It takes three
arguments: start iterator, end iterator and function to
apply(printElement() in this case)
• printElement() is the function applied to each element in
the container

You might also like