This is just the initial blog of my new tech blog series to express my understanding of various concept and constructs of C/C++ programming language. So if there are any discrepancies, I hope the reader will point it out and let me know. The subjects will be random. Today we will discuss template in C++.
There are two types of temples.

  1. Function templates(we will discuss it today)
  2. Class templates

So what is a template?
Templates are something that helps us to write generic programs.
Like, in general, if want to swap to two integer number then we will have a method taking at least two int parameter or reference or pointer of the int parameter.
the function can be declared as.
void swap(int& a,int& b);
and defined as
void swap(int& a,int& b){ 
    int temp;
    temp = a;
    a = b;
    b = temp;
}
But what if we want to swap two float number, then by the existing tool prior to templates we have to write another function with the same name but with different parameters (float ).That's where the template thing comes in the picture. it allows us to write a generic swap function which will allow us to pass any kind of parameter to swap. actually, the compiler will create different versions of the swap function for each data type provided to it and at run time it will call appropriate version of the function. we will declare and define a template function in the following way.
template <typename T>
void Swap(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
This way we can achive the goal of generic programming.
to call the function we will use normal function calls like.
int a=2,b=3;
float c=2.1,d=3.1;
swap(a,b);
swap(c,d);
I will go into detail in the next post. this is just an overview of what template is.



Comments

Popular posts from this blog

Github link