In C++, a function (or a class) works for a set of parameters (or data members) with some predefined data type. If we want that function to work for other data types as well, we would have to overload the function, by copying the entire code and changing only the data type. As you can imagine, this is a cumbersome process, invoking redundancy in your code. An example of such a situation is when you have two similar functions which involve division, but one function works on floats, and the other on ints.
Templates provide us a way to define a set of functions or classes which are algorithmically the same, but differ in data types. In other words, we can re-use the source code with the help of templates. This way we can have one code for all data types, and no code duplication. This is what generic programming is all about - you create generic constructs such as generic functions that work for any arbitrary inputs, or generic classes that encompass all data types. Templates are also useful in meta-programming. They are also known as type parametrization.
Templates can be of two types:
function templates and
class templates.
Function templates:
We define function templates for operations on numerous data types. For example:
template <class T>
T add(T a, T b)
{
return a + b ;
};
This will work for all the following function calls:
add(3,4);
add(3.14,4.90);
add(string_1,string_2);
We can also use
template <typename T
> instead of
template <class T
>.
Here is a trivial working example:
#include <iostream>
using namespace std;
template <typename T>
T add(T a, T b)
{
return a + b ;
};
int main()
{
string a="abc",b="def";
cout<<add(3,4)<<add(4.01,5.9)<<add(a,b);
return 0;
}
Note: What if your function doesn't have a parameter? In that case, call the function as
function<void>();
Class Templates:
Class templates are similarly defined as a regular class definition along with the template keyword. An example:
#include <iostream>
using namespace std;
template <class t>
class A
{
int a;
public:
A() ;
~A() ;
void display();
} ;
template <class t>
A<t>::A()
{
}
template <class t>
A<t>::~A()
{
}
template <class t>
void A<t>::display()
{
cout<<"hello";
}
int main()
{
A<int> a1 ;
A<float> a2 ;
A<void> a3;
a3.display();
return 0;
}