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

Lec Templates

Templates in C++ are used for generic programming. They allow functions and classes to work with different data types without code duplication. Templates get expanded at compile time. There are function templates and class templates. Function templates define a single function that can work with multiple types, while class templates define a class that can work with multiple types. Templates provide flexibility and reuse of code for different data types.

Uploaded by

Muhammad Irfan
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

Lec Templates

Templates in C++ are used for generic programming. They allow functions and classes to work with different data types without code duplication. Templates get expanded at compile time. There are function templates and class templates. Function templates define a single function that can work with multiple types, while class templates define a class that can work with multiple types. Templates provide flexibility and reuse of code for different data types.

Uploaded by

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

Templates

What is Templates in C++?

 used for generic programming


 is defined as a blueprint or formula for creating a generic class or a function.
 can create a single function or single class to work with different data types using
templates.
 C++ template is also known as generic functions or classes
 is a very powerful feature in C++.
 A keyword “template” is used for the template’s syntax and angled bracket in a
parameter (t), which defines the data type variable.
How do templates work in C++?

 it gets expanded at compiler time, just like macros and allows a function or class to
work on different data types without being rewritten.
Types of Templates in C++

• Function template
• Class templates
What is the function template in C++?
 single function template that works with multiple data types simultaneously

 C++ Function Template Syntax:

template<class type>ret-type func-name(parameter list)


{
//body of the function
}
#include <iostream>
using namespace std;

template <typename T>


T add(T num1, T num2) { 2+3=5
return (num1 + num2);
} 2.2 + 3.3 = 5.5

int main() {
int result1;
double result2;
// calling with int parameters
result1 = add<int>(2, 3);
cout << "2 + 3 = " << result1 << endl;

// calling with double parameters


result2 = add<double>(2.2, 3.3);
cout << "2.2 + 3.3 = " << result2 << endl;

return 0;
}
#include <iostream>
using namespace std;
7
// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded 7
template <typename T> T myMax(T x, T y)
{ g
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

return 0;
}
template <class T> void bubbleSort(T a[], int
n)
{
for (int i = 0; i < n - 1; i++)
Sorted array : 10 20 30 40 50
for (int j = n - 1; i < j; j--)
if (a[j] < a[j - 1])
swap(a[j], a[j - 1]);
}
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] << " ";
cout << endl;

return 0;
}
#include <iostream>
using namespace std;
template<class T> T add(T &a,T &b) Addition of i and j is :5
{
T result = a+b; Addition of m and n is :3.5
return result;

}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<'\n';
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
Class Templates:

 Class Template Declaration

template <class T>


class className {
private:
T var; ... .. ...
public:
T functionName(T arg);
... .. ... };
Creating a Class Template Object

className<dataType> classObject;

Example:
className<int> classObject;
className<float> classObject;
className<string> classObject;
// Class template
template <class T>
class Number {
private:
// Variable of type T int Number = 7 double Number =
T num; 7.7
public: Number(T n) : num(n) {} // constructor
T getNum() {
return num;
} };
int main() {
// create object with int type
Number<int> numberInt(7);
// create object with double type
Number<double> numberDouble(7.7);
cout << "int Number = " << numberInt.getNum() << endl;
cout << "double Number = " << numberDouble.getNum() << endl;
return 0;
}
Defining a Class Member Outside the Class Template

template <class T>


class ClassName {
... .. ...
// Function prototype
returnType functionName();
};
// Function definition
template <class T>
returnType ClassName<T>::functionName() {
// code
}
#include <iostream> void displayResult() { Int results:
using namespace std; cout << "Numbers: " << num1 << " and " << num2 << "." << endl;
cout << num1 << " + " << num2 << " = " << add() << endl; Numbers: 2 and 1.
template <class T> cout << num1 << " - " << num2 << " = " << subtract() << endl;
class Calculator { cout << num1 << " * " << num2 << " = " << multiply() << endl; 2+1=3
private: cout << num1 << " / " << num2 << " = " << divide() << endl;
T num1, num2; } 2-1=1

public: T add() { return num1 + num2; } 2*1=2


Calculator(T n1, T n2) { T subtract() { return num1 - num2; }
num1 = n1; T multiply() { return num1 * num2; } 2/1=2
num2 = n2; T divide() { return num1 / num2; }
} };
int main() { Float results:
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2); Numbers: 2.4 and 1.2.
cout << "Int results:" << endl; 2.4 + 1.2 = 3.6
intCalc.displayResult();
2.4 - 1.2 = 1.2
cout << endl
<< "Float results:" << endl; 2.4 * 1.2 = 2.88
floatCalc.displayResult();
2.4 / 1.2 = 2
return 0;
}
C++ Class Templates With Multiple Parameters

template <class T, class U, class V = int>


class ClassName {
private:
T member1;
U member2;
V member3;
... .. ...
public:
... .. ...
};
#include <iostream>
using namespace std;
// Class template with multiple and default parameters
template <class T, class U, class V = char>
class ClassTemplate {
private:
T var1; obj1 values:
U var2; var1 = 7
V var3; var2 = 7.7
public: ClassTemplate(T v1, U v2, V v3) : var1(v1), var2(v2), var3(v3) {} var3 = c
void printVar() { obj2 values:
cout << "var1 = " << var1 << endl; var1 = 8.8
cout << "var2 = " << var2 << endl; var2 = a
cout << "var3 = " << var3 << endl; } }; var3 = 0

int main() {
// create object with int, double and char types
ClassTemplate<int, double> obj1(7, 7.7, 'c’);
cout << "obj1 values: " << endl;
obj1.printVar();
// create object with int, double and bool types
ClassTemplate<double, char, bool> obj2(8.8, 'a', false);
cout << "\nobj2 values: " << endl;
obj2.printVar();
return 0;
}
 What is the difference between function overloading and templates?
 can we overload a template function or class?
 What happens when there is a static member in a template class/function?
 What is template specialization?
 Can we pass non type parameters to templates?
 What is Standard Template Library in C++

You might also like