Templates


It is an approach where generic types are used as parameters in algorithms so that they work for a variety of suitable data types and data structures. Generic classes Generic functions Class template- For eg. An array class for multiple data types(int , float etc.). Function template- For eg. A function mul() for multiplying int, float, double data types. A template is a mechanism that allows you to create functions and classes that can be reused with every data types. Template is defined with a parameter that would be replaced, the templates are sometimes called as parameterized classes or functions.

Examples


#include <iostream.h> Template<class T> Void swap(T &x, T &y) { T temp= x; x=y; y= temp; } Void fun(int m, int n,float a, float b) { cout<<m and n before swap:<<m<<“”<<n; swap(m,n); cout<< m and n after swap:<<m<<“”<<n; } cout<<a and b before swap:<<a<<“”<<b; swap(a,b); cout<< a and b after swap:<<a<<“”<<b; { Int main() { fun(10,30,23.32,45.32); Return 0; }