Lec Templates
Lec Templates
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
int main() {
int result1;
double result2;
// calling with int parameters
result1 = add<int>(2, 3);
cout << "2 + 3 = " << result1 << 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]);
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:
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
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++