2. TEMPLATES
• 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.
3. • A template parameter is a special kind of
parameter that can be used to pass a type as
argument: just like regular function
parameters can be used to pass values to a
function, template parameters allow to pass
also types to a function.
• These function templates can use these
parameters as if they were any other regular
type.
4. Example:
• Consider a situation where we have to sort list
of students according to their roll number and
their percentage. Since roll number is of
integer type and percentage is of float type, we
need to write separate sorting algorithm for
this problem.
• But using template we can define a generic
data type for sorting which can be replaced
later by integer and float data type.
5. • The format for declaring function templates with type
parameters is:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
• The only difference between both prototypes is the use
of either the keyword class or the keyword typename.
• Its use is indistinct, since both expressions have exactly
the same meaning and behave exactly the same way.
6. Need for Function Templates
• Templates are instantiated at compile time
with the source code.
• It uses less code than overloaded C++
functions.
• It is type safe.
• It allows user-defined specialization.
• It allow non-type parameters.
8. Classification of Templates
The concept of templates can be used in two
different ways:
• Function Templates
• Class Templates
9. Function Template
• 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.
10. 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)
{
... .. ...
}
11. • 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.
12. Example 1: Function Template to find the largest
number
#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;
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;
}
13. OUTPUT:
Enter two integers:
5
10
10 is larger.
Enter two floating-point numbers:
12.4
10.2
12.4 is larger.
Enter two characters:
z
Z
z has larger ASCII value.
14. Explanation:
• 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.
15. • 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.
16. Example 2: Swap Data Using Function Templates
#include <iostream>
using namespace std;
template <typename T>
void Swap(T &n1, T &n2)
{
T temp;
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 << "nnAfter passing data to
function template.n";
cout << "i1 = " << i1 << "ni2 = " << i2;
cout << "nf1 = " << f1 << "nf2 = " << f2;
cout << "nc1 = " << c1 << "nc2 = " <<
c2;
return 0;
}
17. 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
18. • 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.
19. Example 3 : Searching an Element
#include <iostream>
#include<conio.h>
#include<stdlib.h>
#define MAX_SIZE 5
using namespace std;
// Template Declaration
template<class T>
// Generic Template Function for Search
T getSearch(T x[], T element) {
int i;
cout << "nYour Data :";
for (i = 0; i < MAX_SIZE; i++) {
cout << "t" << x[i];
}
/* for : Check elements one by one - Linear */
for (i = 0; i < MAX_SIZE; i++) {
/* If for Check element found or not */
if (x[i] == element) {
cout << "nFunction Template : Element :
" << element << " : Found : Position : " << i + 1
<< ".n";
break;
}
}
if (i == MAX_SIZE)
cout << "nSearch Element : " << element
<< " : Not Found n";
}
20. int main() {
int arr_search[MAX_SIZE], i, element;
float f_arr_search[MAX_SIZE],
f_element;
cout << "Simple Function Template Array
Program Example : Search Numbern";
cout << "nEnter " << MAX_SIZE << "
Elements for Searching Int : " << endl;
for (i = 0; i < MAX_SIZE; i++)
cin >> arr_search[i];
cout << "nEnter Element to Search
(Int) : ";
cin>>element;
// Passing int Array to Template
Function
getSearch(arr_search, element);
cout << "nEnter " << MAX_SIZE << "
Elements for Searching Float : " << endl;
for (i = 0; i < MAX_SIZE; i++)
cin >> f_arr_search[i];
cout << "nEnter Element to Search
(Float) : ";
cin>>f_element;
// Passing int Array to Template
Function
getSearch(f_arr_search, f_element);
getch();
return 0;
}
21. Output:
Simple Function Template Array Program Example : Search Number
Enter 5 Elements for Searching Int :
56
34
100
23
90
Enter Element to Search (Int) : 23
Your Data : 56 34 100 23 90
Function Template Search : Element : 23 : Found : Position : 4.
Enter 5 Elements for Searching Float :
45.23
89.01
90.67
100.89
23.90
Enter Element to Search (Float) : 23.90
Your Data : 45.23 89.01 90.67 100.89 23.9
Function Template Search : Element : 23.9 : Found : Position : 5.
22. Example 4: Sum of Elements
#include <iostream>
using namespace std;
template <typename T>
T sum( T x, T y)
{
return x + y;
}
int main()
{
cout << "Sum : " <<
sum(3, 5) << endl;
cout << "Sum : " <<
sum(3.0, 5.2) << endl;
cout << "Sum : " <<
sum(3.24234, 5.24144) <<
endl;
return 0;
}
24. Overloading Function Templates
• A template function overloads itself as
needed.
• But we can explicitly overload it too.
• Overloading a function template means
having different sets of function templates
which differ in their parameter list.
25. • The function template can also be overloaded
with multiple declarations.
• It may be overloaded either by functions of its
mane or by template functions of the same
name.
• Similar to overloading of normal functions,
overloaded functions must differ either in
terms of number of parameter or their types.
26. #include <iostream>
template <class X> void func(X
a)
{
// Function code;
cout <<”Inside f(X a) n”;
}
template <class X, class Y>
void func(X a, Y b)
//overloading function
template func()
{
// Function code;
cout <<”Inside f(X a, Y b)
n”;
}
int main()
{
func(10); // calls func(X a)
func(10, 20); // calls func(X
a, Y b)
return 0;
}
29. Example
#include <iostream>
using namespace std;
template<class X> void
fun(X a)
{
std::cout << "Value of a
is : " <<a<< std::endl;
}
template<class X,class Y>
void fun(X b ,Y c)
{
std::cout << "Value of b
is : " <<b<< std::endl;
std::cout << "Value of c
is : " <<c<< std::endl;
}
int main()
{
fun(10);
fun(20,30.5);
return 0;
}