0% found this document useful (0 votes)
7 views22 pages

Oop Lec12

The document discusses templates in C++, which allow for the creation of generic functions and classes that can operate with different data types. It covers function templates and class templates, providing examples such as finding the largest number and implementing a simple calculator. The document emphasizes the benefits of code reusability and flexibility that templates offer in programming.

Uploaded by

lucky420130
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)
7 views22 pages

Oop Lec12

The document discusses templates in C++, which allow for the creation of generic functions and classes that can operate with different data types. It covers function templates and class templates, providing examples such as finding the largest number and implementing a simple calculator. The document emphasizes the benefits of code reusability and flexibility that templates offer in programming.

Uploaded by

lucky420130
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/ 22

Object Oriented Programming

Week 12
Lecture 1 & 2
Templates are powerful features of C++ which allows you to write generic programs. In simple
terms, you can create a single function or a class to work with different data types using
templates.

Templates are often used in larger codebase for the purpose of code reusability and flexibility of
the programs.

The concept of templates can be used in two different ways:

Function Templates

Class Templates

Function Templates
A function template works in a similar to a normal function, with one key difference.

A single function template can work with different data types at once but, a single normal
function can only work with one set of data types.

Normally, if you need to perform identical operations on two or more types of data, you use
function overloading to create two functions with the required function declaration.

However, a better approach would be to use function templates because you can perform the
same task writing less and maintainable code.

How to declare a function template?


A function template starts with the keyword template followed by template parameter/s
inside < > which is followed by function declaration.

template <class T>

T someFunction(T arg)

... .. ...

Page 1 of 22
Object Oriented Programming

In the above code, T is a template argument that accepts different data types (int, float),
and class is a keyword.

You can also use keyword typename instead of class in the above example.

When, an argument of a data type is passed to someFunction( ), compiler generates a new


version of someFunction() for the given data type.

Example 1: Function Template to find the largest number

Program to display largest among two numbers using function templates.

// If two characters are passed to function template, character with larger ASCII value is
displayed.

#include <iostream>

using namespace std;

// template function

template <class T>

T Large(T n1, T n2)

return (n1 > n2) ? n1 : n2;

int main()

int i1, i2;

float f1, f2;

char c1, c2;

Page 2 of 22
Object Oriented Programming

cout << "Enter two integers:\n";

cin >> i1 >> i2;

cout << Large(i1, i2) <<" is larger." << endl;

cout << "\nEnter two floating-point numbers:\n";

cin >> f1 >> f2;

cout << Large(f1, f2) <<" is larger." << endl;

cout << "\nEnter two characters:\n";

cin >> c1 >> c2;

cout << Large(c1, c2) << " has larger ASCII value.";

return 0;

Output

Enter two integers:

10

10 is larger.

Enter two floating-point numbers:

12.4

10.2

12.4 is larger.

Page 3 of 22
Object Oriented Programming

Enter two characters:

z has larger ASCII value.

In the above program, a function template Large() is defined that accepts two
arguments n1 and n2 of data type T. T signifies that argument can be of any data type.

Large() function returns the largest among the two arguments using a simple conditional
operation.

Inside the main() function, variables of three different data types: int, float and char are declared.
The variables are then passed to the Large() function template as normal functions.

During run-time, when an integer is passed to the template function, compiler knows it has to
generate a Large() function to accept the int arguments and does so.

Similarly, when floating-point data and char data are passed, it knows the argument data types
and generates the Large() function accordingly.

This way, using only a single function template replaced three identical normal functions and
made your code maintainable.

Example 2: Swap Data Using Function Templates

Program to swap data using function templates.

#include <iostream>

using namespace std;

template <typename T>

void Swap(T &n1, T &n2)

T temp;

Page 4 of 22
Object Oriented Programming

temp = n1;

n1 = n2;

n2 = temp;

int main()

int i1 = 1, i2 = 2;

float f1 = 1.1, f2 = 2.2;

char c1 = 'a', c2 = 'b';

cout << "Before passing data to function template.\n";

cout << "i1 = " << i1 << "\ni2 = " << i2;

cout << "\nf1 = " << f1 << "\nf2 = " << f2;

cout << "\nc1 = " << c1 << "\nc2 = " << c2;

Swap(i1, i2);

Swap(f1, f2);

Swap(c1, c2);

cout << "\n\nAfter passing data to function template.\n";

cout << "i1 = " << i1 << "\ni2 = " << i2;

cout << "\nf1 = " << f1 << "\nf2 = " << f2;

cout << "\nc1 = " << c1 << "\nc2 = " << c2;

Page 5 of 22
Object Oriented Programming

return 0;

Output

Before passing data to function template.

i1 = 1

i2 = 2

f1 = 1.1

f2 = 2.2

c1 = a

c2 = b

After passing data to function template.

i1 = 2

i2 = 1

f1 = 2.2

f2 = 1.1

c1 = b

c2 = a

In this program, instead of calling a function by passing a value, a call by reference is issued.

The Swap() function template takes two arguments and swaps them by reference.

Page 6 of 22
Object Oriented Programming

Class Templates
Like function templates, you can also create class templates for generic class operations.

Sometimes, you need a class implementation that is same for all classes, only the data types used
are different.

Normally, you would need to create a different class for each data type OR create different
member variables and functions within a single class.

This will unnecessarily bloat your code base and will be hard to maintain, as a change is one
class/function should be performed on all classes/functions.

However, class templates make it easy to reuse the same code for all data types.

How to declare a class template?


template <class T>

class className

... .. ...

public:

T var;

T someOperation(T arg);

... .. ...

};

In the above declaration, T is the template argument which is a placeholder for the data type
used.

Inside the class body, a member variable var and a member function someOperation() are both of
type T.

How to create a class template object?


To create a class template object, you need to define the data type inside a < > when creation.

Page 7 of 22
Object Oriented Programming

className<dataType> classObject;

For example:

className<int> classObject;

className<float> classObject;

className<string> classObject;

Example 3: Simple calculator using Class template

Program to add, subtract, multiply and divide two numbers using class template

#include <iostream>

using namespace std;

template <class T>

class Calculator

private:

T num1, num2;

public:

Calculator(T n1, T n2)

num1 = n1;

num2 = n2;

void displayResult()

Page 8 of 22
Object Oriented Programming

cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;

cout << "Addition is: " << add() << endl;

cout << "Subtraction is: " << subtract() << endl;

cout << "Product is: " << multiply() << endl;

cout << "Division is: " << divide() << endl;

T add() { return num1 + num2; }

T subtract() { return num1 - num2; }

T multiply() { return num1 * num2; }

T divide() { return num1 / num2; }

};

int main()

Calculator<int> intCalc(2, 1);

Calculator<float> floatCalc(2.4, 1.2);

cout << "Int results:" << endl;

intCalc.displayResult();

cout << endl << "Float results:" << endl;

Page 9 of 22
Object Oriented Programming

floatCalc.displayResult();

return 0;

Output

Int results:

Numbers are: 2 and 1.

Addition is: 3

Subtraction is: 1

Product is: 2

Division is: 2

Float results:

Numbers are: 2.4 and 1.2.

Addition is: 3.6

Subtraction is: 1.2

Product is: 2.88

Division is: 2

In the above program, a class template Calculator is declared.

The class contains two private members of type T: num1 & num2, and a constructor to initalize
the members.

It also contains public member functions to calculate the addition, subtraction, multiplication and
division of the numbers which return the value of data type defined by the user. Likewise, a
function displayResult() to display the final output to the screen.

In the main() function, two different Calculator objects intCalc and floatCalc are created for data
types: int and float respectively. The values are initialized using the constructor.

Page 10 of 22
Object Oriented Programming

Notice we use <int> and <float> while creating the objects. These tell the compiler the data type
used for the class creation.

This creates a class definition each for int and float, which are then used accordingly.

Then, displayResult() of both objects is called which performs the Calculator operations and
displays the output.

Page 11 of 22
Object Oriented Programming

Templates in C++
 Difficulty Level : Medium
 Last Updated : 13 Apr, 2021
A template is a simple and yet very powerful tool in C++. The simple idea is to pass data
type as a parameter so that we don’t need to write the same code for different data types.
For example, a software company may need sort() for different data types. Rather than
writing and maintaining the multiple codes, we can write one sort() and pass data type as
a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The
second keyword can always be replaced by keyword ‘class’.
How do templates work?
Templates are expanded at compiler time. This is like macros. The difference is, the
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.

Function Templates We write a generic function that can be used for different data

Page 12 of 22
Object Oriented Programming

types. Examples of function templates are sort(), max(), min(), printArray().


Know more on Generics in C++

 CPP

#include <iostream>

using namespace std;

// One function works for all data types. This would work

// even for user defined types if operator '>' is overloaded

template <typename T>

T myMax(T x, T y)

return (x > y)? x: y;

int main()

cout << myMax<int>(3, 7) << endl; // Call myMax for int

cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double

cout << myMax<char>('g', 'e') << endl; // call myMax for char

Page 13 of 22
Object Oriented Programming

return 0;

Output:
7
7
g

Below is the program to implement Bubble Sort using templates in C++:

 CPP

// CPP code for bubble sort

// using template function

#include <iostream>

using namespace std;

// A template function to implement bubble sort.

// We can use this for any data type that supports

// comparison operator < and swap works for it.

Page 14 of 22
Object Oriented Programming

template <class T>

void bubbleSort(T a[], int n) {

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

for (int j = n - 1; i < j; j--)

if (a[j] < a[j - 1])

swap(a[j], a[j - 1]);

// Driver Code

int main() {

int a[5] = {10, 50, 30, 40, 20};

int n = sizeof(a) / sizeof(a[0]);

// calls template function

bubbleSort<int>(a, n);

cout << " Sorted array : ";

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

cout << a[i] << " ";

Page 15 of 22
Object Oriented Programming

cout << endl;

return 0;

Output:

Sorted array : 10 20 30 40 50

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.

 CPP

#include <iostream>

using namespace std;

template <typename T>

class Array {

private:

T *ptr;

int size;

Page 16 of 22
Object Oriented Programming

public:

Array(T arr[], int s);

void print();

};

template <typename T>

Array<T>::Array(T arr[], int s) {

ptr = new T[s];

size = s;

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

ptr[i] = arr[i];

template <typename T>

void Array<T>::print() {

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

cout<<" "<<*(ptr + i);

cout<<endl;

Page 17 of 22
Object Oriented Programming

int main() {

int arr[5] = {1, 2, 3, 4, 5};

Array<int> a(arr, 5);

a.print();

return 0;

Output:
12345

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.

 CPP

#include<iostream>

using namespace std;

template<class T, class U>

class A {

T x;

Page 18 of 22
Object Oriented Programming

U y;

public:

A() { cout<<"Constructor Called"<<endl; }

};

int main() {

A<char, char> a;

A<int, double> b;

return 0;

Output:
Constructor Called
Constructor Called

Can we specify default value for template arguments?


Yes, like normal parameters, we can specify default arguments to templates. The
following example demonstrates the same.

 CPP

#include<iostream>

using namespace std;

Page 19 of 22
Object Oriented Programming

template<class T, class U = char>

class A {

public:

T x;

U y;

A() { cout<<"Constructor Called"<<endl; }

};

int main() {

A<char> a; // This will call A<char, char>

return 0;

Output:
Constructor Called

What is the difference between function overloading and templates?


Both function overloading and templates are examples of polymorphism features of OOP.
Function overloading is used when multiple functions do similar operations, templates
are used when multiple functions do identical operations.
What is template specialization?
Template specialization allows us to have different codes for a particular data type.
See Template Specialization for more details.
Can we pass non-type parameters to templates?
We can pass non-type arguments to templates. Non-type parameters are mainly used for

Page 20 of 22
Object Oriented Programming

specifying max or min values or any other constant value for a particular instance of a
template. The important thing to note about non-type parameters is, they must be const.
The compiler must know the value of non-type parameters at compile time. Because the
compiler needs to create functions/classes for a specified non-type value at compile time.
In the below program, if we replace 10000 or 25 with a variable, we get a compiler error.
Please see this.
Below is a C++ program.

 CPP

// A C++ program to demonstrate working of non-type

// parameters to templates in C++.

#include <iostream>

using namespace std;

template <class T, int max>

int arrMin(T arr[], int n)

int m = max;

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

if (arr[i] < m)

m = arr[i];

Page 21 of 22
Object Oriented Programming

return m;

int main()

int arr1[] = {10, 20, 15, 12};

int n1 = sizeof(arr1)/sizeof(arr1[0]);

char arr2[] = {1, 2, 3};

int n2 = sizeof(arr2)/sizeof(arr2[0]);

// Second template parameter to arrMin must be a constant

cout << arrMin<int, 10000>(arr1, n1) << endl;

cout << arrMin<char, 256>(arr2, n2);

return 0;

Output:
10
1

Page 22 of 22

You might also like