Templates in C++

Templates are used to support generic programming  in C++, what happens when you need a function of a class that takes its argument  as float as well as integer. You have to declare and define two functions, the first one  takes parameters of the type integer and another float . Further,  templates make life easy, in  a template you can define your own data type which is unknown in example we have declared DT, and that will be replaced by compiler and compiler may create several copies of the functions with different types argument.
__________________________________
#include <iostream>
using namespace std;
template<class  DT>
class Division{
DT dt1;
public:
void divide(DT x, DT y)
{
DT dt1;
x=17;
y=5;
dt1=x/y;
cout<< dt1<<endl;
}
};
int main(int argc, char **argv)
{
Division <int> dv1;
dv1.divide(17,5);
return 0;
}
_____________________________

Program description- In the program we have declared class division which has one variable of type  DT and one function and a function divide that can accept DT types of variables but it does not return anything  in main class in bracket  <> if we put int DT will be of integer type and when inside <> type is float DT will be of float type in program we have passed 17 and 5 and divide function divides 17 by 5 when we put int the result would be 3 because decimal part is truncated
and when it is float the result would be 3.4. To see the program execution  see the video.

Conclusion- In this post, I have tried to make you basics about templates, hope this will be helpful for you. If you find any error or want to suggest feel free to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.