In this tutorial we shall learn about below points:
1. Introduction to template programming.
1. Templates are very important topic in C++. With the help of templates we can write functions that will work with any type of data types.
2. A function that works with any data type is called as generic function.
3. This type of programming where the type will be specified later is called as generic programming.
2. What is the need for Templates
1. Templates help us to create 1 function that will work with different data types.
2. So there is no need to different functions for different data types.
Consider simple program that needs to calculate the sum of 2 values.
Normally the program will look like below:
#include <iostream>
using namespace std;
void sum(int a, int b)
{
cout<<"Calling Int, sum of "<<a <<" "<<b<<" is = "<<(a+b)<<endl;
}
void sum(double a, double b)
{
cout<<"Calling Double, sum of "<<a <<" "<<b<<" is = "<<(a+b)<<endl;
}
int main(void)
{
sum(1, 2);
sum(1.2, 1.4);
}
Output:
Calling Int, sum of 1 2 is = 3
Calling Double, sum of 1.2 1.4 is = 2.6
But by using template function, we can modify it as below:
#include <iostream>
using namespace std;
template <class T>
void sum(T a, T b)
{
cout<<"Calling template function, sum of "<<a <<" "<<b<<" is = "<<(a+b)<<endl;
}
int main(void)
{
sum(1, 2);
sum(1.2, 1.4);
}
Output:
Calling Int, sum of 1 2 is = 3
Calling Double, sum of 1.2 1.4 is = 2.6
We shall learn in-depth about template in next chapters.
So once we write a template function, the compiler will check what different kinds of data types that the template function is being called and will create functions according to those different data types.
Some of the advantages of Template Programming or Generic Programming is:
1. Code reusability
2. No need to write overloaded methods.
3. One function will work with any data type.
3. Different types of templates
Below are the different types of templates that we are going to learn in coming chapters.
1. Class Template
2. Function Template
3. Member function Templates
4. Class template with Overloaded Operators
5. Class templates and Inheritance
4. Important points to be remembered while doing template programming
Below are some of the points that needs to be remembered while doing template programming. Probably you can visit this again after completing all the template chapters.
1. You can assign default value to template functions.
template <class T, int num = 20>
class MyClass
{
T arr[num];
}
2. Template functions can be used in inheritance also.
template<class T>
class Derived: public Base<t>
3. You should use all the template argument that you have defined. If you don’t use, compiler will give an error.
template <class T>
T display(void)
{
return 10;
}
The above program will give an error.