100% found this document useful (1 vote)
30 views13 pages

Chapter 1, Unit - IV (Templates)

Uploaded by

shagunverma504
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
30 views13 pages

Chapter 1, Unit - IV (Templates)

Uploaded by

shagunverma504
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Templates in C++ with Examples

A template is a simple yet very powerful tool in C++. The simple idea is to
pass the 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
to sort() for different data types. Rather than writing and maintaining
multiple codes, we can write one sort() and pass the datatype as a
parameter.
C++ adds two new keywords to support templates: ‘template’ and
‘typename’. The second keyword can always be replaced by the keyword
‘class’.

How Do Templates Work?


Templates are expanded at compiler time. This is like macros. The
difference is, that 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 the same function/class.

Function Templates
We write a generic function that can be used for different data types.
Examples of function templates are sort(), max(), min(), printArray().
// C++ Program to demonstrate
// Use of template
#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()
{
// Call myMax for int
cout << myMax<int>(3, 7) << endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0) << endl;
// call myMax for char
cout << myMax<char>('g', 'e') << endl;

return 0;
}

Class Templates
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.
// C++ Program to implement
// template Array class
#include <iostream>
using namespace std;

template <typename T> class Array {


private:
T* ptr;
int size;

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;
}

int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
Array<int> a(arr, 5);
a.print();
return 0;
}

Can there be more than one argument for templates?

Yes, like normal parameters, we can pass more than one data type as
arguments to templates. The following example demonstrates the same.

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
quite similar (not identical) operations, templates are used when multiple
functions do identical operations.

Generic Programming with Templates


Generics is the idea to allow type (Integer, String, … etc and user-defined
types) to be a parameter to methods, classes and interfaces. For example,
classes like an array, map, etc, which can be used using generics very
efficiently. We can use them for any type.
The method of Generic Programming is implemented to increase the
efficiency of the code. Generic Programming enables the programmer to
write a general algorithm which will work with all data types. It eliminates
the need to create different algorithms if the data type is an integer, string or
a character.
The advantages of Generic Programming are
1. Code Reusability

2. Avoid Function Overloading

3. Once written it can be used for multiple times and cases.

Generics can be implemented in C++ using Templates. 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.

Generic Functions using Template:

We write a generic function that can be used for different data types.
Examples of function templates are sort(), max(), min(), printArray()
#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()
{

// Call myMax for int


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

// call myMax for double


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

// call myMax for char


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

return 0;
}

Generic Class using Template:

Like function templates, class templates are useful when a class defines
something that is independent of data type. Can be useful for classes like
LinkedList, binary tree, Stack, Queue, Array, etc.
Following is a simple example of template Array class.
#include <iostream>

using namespace std;

template <typename T>

class Array {

private:

T* ptr;

int size;

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;

}
int main()

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

Array<int> a(arr, 5);

a.print();

return 0;

Overloading function templates in C++


Template:

● A template is a tool that reduces the efforts in writing the same

code as templates can be used at those places.

● A template function can be overloaded either by a non-template


function or using an ordinary function template.

Function Overloading: In function overloading, the function may have the


same definition, but with different arguments. Below is the C++ program
to illustrate function overloading:

// C++ program to demonstrate the


// function overloading
#include <bits/stdc++.h>
using namespace std;

// Function to calculate square


void square(int a)
{
cout << "Square of " << a
<< " is " << a * a
<< endl;
}

// Function to calculate square


void square(double a)
{
cout << "Square of " << a
<< " is " << a * a
<< endl;
}

// Driver Code
int main()
{
// Function Call for side as
// 9 i.e., integer
square(9);

// Function Call for side as


// 2.25 i.e., double
square(2.25);
return 0;
}
Explanation:

● In the above code, the square is overloaded with different

parameters.

● The function square can be overloaded with other arguments too,

which requires the same name and different arguments every

time.

● To reduce these efforts, C++ has introduced a generic type called

function template.

Function Template: The function template has the same syntax as a


regular function, but it starts with a keyword template followed by
template parameters enclosed inside angular brackets <>.

template <class T>

T functionName(T arguments)
{
// Function definition
………. …… ….. …….
}
where, T is template argument accepting different arguments and class is
a keyword.

Template Function Overloading:

● The name of the function templates are the same but called with

different arguments is known as function template overloading.

● If the function template is with the ordinary template, the name of

the function remains the same but the number of parameters

differs.

● When a function template is overloaded with a non-template

function, the function name remains the same but the function’s

arguments are unlike.

// C++ program to illustrate overloading


// of template function using an
// explicit function
#include <bits/stdc++.h>
using namespace std;

// Template declaration
template <class T>
// Template overloading of function
void display(T t1)
{
cout << "Displaying Template: "
<< t1 << "\n";
}

// Template overloading of function


void display(int t1)
{
cout << "Explicitly display: "
<< t1 << "\n";
}

// Driver Code
int main()
{
// Function Call with a
// different arguments
display(200);
display(12.40);
display('G');

return 0;
}

You might also like