0% found this document useful (0 votes)
15 views40 pages

PPT11 Templates

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)
15 views40 pages

PPT11 Templates

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/ 40

UTA 018: OOPs

Templates in C++

1
Introduction
Templates in C++ allow you to write generic code that can work with any
data type. Instead of writing multiple versions of the same function or class
for different data types, templates let you create type-independent functions
and classes that automatically adapt to the type of data they work with.
• Templates come in two main forms:
• Function Templates: Used to create functions that can operate on any data type.
• Class Templates: Used to create classes that can store, manipulate, or process data of
any type.
Templates are a cornerstone of generic programming in C++, providing
flexibility, reusability, and type safety.
Need of Template
• To reduce code duplication when supporting numerous data types

int MaxElement (int x, int y){ return x > y ? x : y ; }


float MaxElement (float x, float y){ return x > y ? x : y ; }
char MaxElement (char x, char y){ return x > y ? x : y ; }

T MaxElement (T x, T y){ return x>y?x:y;}


We can write a generic code for a We can write a generic code for a class, to
function e.g. add() for integers, double, manipulate group of member variables &
float etc. functions e.g. linked list of strings, integers
etc.
Function Template
A template function is a function that works with any data type. Instead of
specifying a particular data type, you use a placeholder type. When the
function is called, the compiler replaces the placeholder type with the actual
data type of the argument(s).

Syntax of a Template Function:


template <class/typename T>
T functionName(T parameter1, T parameter2,…T Parameter_n)
{
// Function implementation
}
Example:1
#include <iostream>
using namespace std;

template <class T> Defining Function Template


T MaxElement(T x, T y){ return x>y?x:y;}

int main(){
cout<<MaxElement (10,20)<<endl;
cout<<MaxElement ('a','z')<<endl; Calling Function Template
cout<<MaxElement (-2.5,7.7)<<endl;
}
Example:2
Example: Bubble Sort without Template
void bubbleSort(int 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]);
}
Example: Bubble Sort with Template
template <class T>
void bubbleSort(T arr[], 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]);
}
Function Template with Multiple Parameters
Example: Write a template for
int main(){
show(100,"hello hello");
show('k',1500);
show(1.23,2987);
}
Example: Write a template for
template <class T1, class T2>
void show(T1 a, T2 b){
cout<<a<<“, “<<b<<endl; int main(){
} show(100,"hello hello");
show('k',1500);
show(1.23,2987);
}
Function template with non-type parameter
• Non-type parameter is not a type (datatype) but a
value e.g. 100
• They are used to initialize a class or to specify the sizes
of class members

• template <class T, int size> // size is the non-type parameter


Function template with non-type parameter
#include<iostream>
using namespace std;
template <class T, int size>
void show(T a){cout<<a<<", "<<size;}
int main(){
show <char,10> ('c');
}
Overloading function templates
template <class T1, class T2>
void show(T1 a, T2 b){
cout<<a<<", "<<b<<endl;
}
void show(int a, int b) {
cout<<”For integer cases";
}

int main(){
show(100,"hello hello");
show(3,3);
}
Usage of Template Argument
• No-argument template function
Template <class T>
T void (void) //error: T is not used as an argument
{
//…..
Return parameter;
}
• Template-type Argument Unused
Template <class T>
Void test (int x) //error: T is not used as an argument
{
//…..
Return parameter;
}

• Usage of partial Number of Template Argument


Template <class T, class U>
Void insert (T &x) //error: U is not used as an argument
{
//…..
Return parameter;
}
Class Template
// Template class example
template <class/typename T> class Test { // Template function example
T var; #include <iostream>
public: using namespace std;
Test (T i) {var=i;} template <class T>
T divideBy2 () {return var/2;} T MaxElement(T x, T y){
}; return x>y?x:y;
int main(){ }
Test <int> t1(50); int main(){
Test <double> t2(-10.20); cout<<MaxElement(10,20)<<endl;
cout<<t1.divideBy2()<<endl; cout<<MaxElement('a','z')<<endl;
cout<<t2.divideBy2()<<endl; }
}
Defining function outside the template class
template <class/typename T>
class Test {
T var;
public:
Test (T i) {var=i;}
T divideBy2 ();
};
template <class T>
T Test<T> :: divideBy2(){return var/2;}
template class with non-type parameter
template <class/typename T, int n>
class Test {
T var;
public:
Test () {var = n; cout<<"n = "<< n <<endl;}
T divideBy2 () {return var/2;}
};
int main(){ Output:
Test <int,10> t1; n = 10
Test <double,20> t2; n = 20
5 10
cout<<t1.divideBy2()<<" "<<t2.divideBy2()<<endl;
}
Class Template with Multiple Parameters
Advantages of Using Templates
• Code Reusability: Templates allow you to write code once and use it
for different data types without duplication.
• Type Safety: The compiler enforces type checking at compile time,
ensuring the correct data type is used.
• Generic Programming: Templates facilitate writing generic algorithms
and data structures, making code more flexible and adaptable.
Template Specialization
Template specialization allows you to define a specific implementation
of a template function or class for a particular type. This is useful when
you need specialized behavior for a certain data type, while still having
a general template for other types.
Example of Class Template Specialization
Example of Class Template Specialization

•Display<int> uses the general Display template, while Display<bool> uses the specialized version
specifically designed for bool.

•This feature is particularly useful when you need customized behavior for certain data
types, such as printing true/false instead of 1/0.
Partial Specialization (Class Templates Only)
Partial specialization is only available for class templates (not function
templates) and allows you to specialize a template for a subset of its
template parameters.
Partial Specialization (Class Templates Only)

Note:
Pair<int, double> uses the general Pair
template, while Pair<int, int> uses the
partially specialized version where both
template parameters are the same.
Variadic Templates
• Variadic templates allow a template to accept an arbitrary number of
template parameters. This is useful for functions like printf-style
functions or containers that handle multiple elements of varying
types.
Note:
•The first print function is the base case for
recursion.

•The second print function is the recursive


function that processes one argument at a time.

•Variadic templates enable flexible function


calls with any number and type of arguments,
making them powerful for generic
programming.
Inheritance of Class Template
Use of templates with respect to inheritance involves the following:
1. Derive a class template from a base class, which is a template class.
2. Derive a class template from a base class, which is a template class
and add more template members in the derived class.
3. Derive a class from a base class which is not a template, and add
template member to that class.
4. Derive a class from a base class which is a template class and
restrict the template feature, so that the derived class and its
derivatives do not have the template feature.
Syntax
template<class T>
class Base{
//template type data and functions
};
template<class T1, …>
class Derive: public Base<T1, …>{
//template type data and functions.
};
Example:01 int main() {
Derived<int> obj(10);
obj.show(); // Call Base class function
obj.display(); // Call Derived class function

return 0;
}
Example:02
int main() {
Derived<int, double> obj(10, 20.5);
obj.show(); // Call Base class function
obj.display(); // Call Derived class function

return 0;
}
Example:03
Example:04
Thank You

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy