0% found this document useful (0 votes)
17 views

Generic Programming Templates

Uploaded by

opninja173
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Generic Programming Templates

Uploaded by

opninja173
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Amity School of Engineering & Technology

Amity School of Engineering &


Technology
B.Tech. IT – 5th Sem.
Software Engineering

1
Amity School of Engineering & Technology

Generic Programming
Amity School of Engineering & Technology

Motivation for Generic Programming in C++


• We’ve looked at procedural programming
– Reuse of code by packaging it into functions
• We’ve also looked at object-oriented programming
– Reuse of code and data by packaging them into classes
• However, these techniques alone have limitations
– Functions are still specific to the types they manipulate
• E.g., swap (int, int) and swap (int *, int *) do essentially same thing
• But, we must write two versions of swap to implement both
– Classes alone are still specific to the types they contain
• E.g., keep an array (not a vector) of dice and an array of players
– Must write similar data structures and code repeatedly
• E.g., adding a new element to an array
• Generic programming aims to relieve these limitations
Amity School of Engineering & Technology

Generic Programming with Templates


•A significant benefit of object-oriented programming is
reusability of code which eliminates redundant coding
•An important feature of C++ called templates strengths this
benefit of OOP and provides great flexibility to the language
•Templates support generic programming, which allows to
develop reusable software components such as functions,
classes, etc.., supporting different data types in a single
framework. For instance, functions such as sort, search, swap
etc.., which support various data types can be developed.
Amity School of Engineering & Technology

Two types of Templates:


• A template in C++ allows the construction of a family of
template
1. Functions (function templates)
2. Classes (class templates)
to perform the same operation on different data types.
• They perform appropriate operations depending on the data
type of parameters passed to them.
• It allows a single template to deal with a generic data type T.
Amity School of Engineering & Technology

Templates: Crucial to C++ Generic Programming


• Templates are used to parameterize classes and functions
with different types
– Function templates do not require explicit declaration of
parameterized types when called
• E.g., swap (i, j);
– Classes require explicit declaration of parameterized types when
instantiated
• E.g., vector<int> v;
• Some compilers require that template definitions be included
with declarations
Amity School of Engineering & Technology

Function Templates
template <typename T>
void swap(T & lhs, T & rhs)
{ • The swap function template
T temp = lhs; takes a single type parameter, T
lhs = rhs; – interchanges values of two passed
rhs = temp; arguments of the parameterized type
}
int main () • Compiler instantiates the function
{
int i = 3; template twice in main
int j = 7; – with type int for the first call
long r = 12; – with type long for the second call
long s = 30; – Note that the compiler infers the
swap (i, j); type each time swap is called
// i is now 7, j is now 3 – Based on the types of the arguments
swap (r, s);
// r is now 30, s is now 12
return 0;
}
Amity School of Engineering & Technology

Class Templates and Inheritance


class ArrayBase • Class templates can inherit from
{ base classes
public: – Or class templates, but must relate
ArrayBase(const int size);
type parameters to those of base
~ArrayBase();
const int size () const; • Here, we’ve separated template
protected: and non-template code
const int m_size; – Non-template base class
}; – Template derived class
– Functions and variables that do not
template <typename T> need to refer to type parameters go
class Array : into the base class
public ArrayBase { • This is useful in many cases
public:
Array(const int size);
– To avoid accidental type errors
~Array(); (ArrayBase doesn’t access T)
private: – To reduce program size (separate
T * m_values; method definitions compiled for
}; Array<int> Array<float> etc.)
Amity School of Engineering & Technology

How templates work?

Templates are expanded at compiler time. This is like


macros. 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.

9
Amity School of Engineering & Technology

10
Amity School of Engineering & Technology

Syntax of defining Function template


template (typename T)
return_type function_name( arguments)
{
Programming statements;
}
Example:
template (typename T) //function template
T add(T a, T b)
{
T c;
c=a + b;
}
Int main()
{
cout<<add <int> (2,3);
cout<< add <float> (3.7, 2.5);
}
11
Amity School of Engineering & Technology

Function Template on Editor


#include <iostream>
int main()
using namespace std; {
// One function works for all data types. cout << myMax<int>(3, 7) << endl;
//This would work // Call myMax for int
// even for user defined types cout << myMax<double>(3.56, 7.34) <<endl;
//if operator '>' is overloaded // call myMax for double
template <typename T> cout << myMax<char>('g', 'e') << endl;
// call myMax for char
T myMax(T x, T y)
return 0;
{ } Output:
return (x > y)? x: y; 7
7.34
}
g 12
Amity School of Engineering & Technology

Class
// CPP code for bubble sort
Template on Editor- Bubble Sort
int main() {
// using template function int a[5] = {10, 50, 30, 40, 20};
#include <iostream> int n = sizeof(a) / sizeof(a[0]);
using namespace std;
// A template function to implement bubble sort. // calls template function
bubbleSort<int>(a, 5);
// We can use this for any data type that supports
// comparison operator < and swap works for it. cout << " Sorted array : ";
template <class T> for (int i = 0; i < n; i++)
void bubbleSort(T a[], int n) cout << a[i] << " ";
cout << endl;
{
for (int i = 0; i < n - 1; i++) return 0;
for (int j = n - 1; i < j; j--) }
if (a[j] < a[j - 1]) Output:
swap(a[j], a[j - 1]); Sorted array : 10 20 30 40 50
} 13
Amity School of Engineering & Technology

Class Templates Like function templates, class templates are useful when a class defines something that
is independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array,
etc. Following is a simple example of template Array class.
template <typename T>
#include <iostream> Array<T>::Array(T arr[], int s) {
using namespace std; ptr = new T[s];
size = s;
template <typename T> for(int i = 0; i < size; i++)
Output:
class Array { ptr[i] = arr[i]; 1 2 3 4 5
}
private: template <typename T>
T *ptr; void Array<T>::print() {
for (int i = 0; i < size; i++)
int size; cout<<" "<<*(ptr + i);
cout<<endl;
public: }
Array(T arr[], int s); int main() {
int arr[5] = {1, 2, 3, 4, 5};
void print(); Array<int> a(arr, 5);
}; a.print(); 14
return 0; }
Amity School of Engineering & Technology

Syntax of Class template


template <class T, class U>
class ABC
{
private: T a;
U b;
public: void x()
{
}
}; 15
Amity School of Engineering & Technology

Can there be more than one arguments to templates?


Yes, like normal parameters, we can pass more than one data types as arguments to
templates. The following example demonstrates the same.
#include<iostream>
using namespace std;

template<class T, class U>


class A {
T x;
U y;
public:
A() { cout<<"Constructor Called"<<endl; }
};

int main() {
A<char, char> a;
A<int, double> b;
return 0;
16
}

You might also like