Templates
Templates
TEMPLATES IN C++
Templates are a feature of the C++ programming language that allows
functions and classes to operate with generic types.
Templates are used to create generalize code.
Often we do code for specific data types but C++ Templates allow us to manipulate
different type of data with the same piece of code.
Template allow us to create a dynamic type which is actually replaced by the calling
type at the run time of the program.
TEMPLATES IN C++
#include<iostream.h>
int Max(int x,int y)
{
if(x>y)
return x;
else
return y;
}
int main()
{
int a=10,b=20,max;
max=Max(a,b);
cout<<“Max Value Is : “<<max;
return 0;
}
Function Template
Syntax :-
template <class T>T myfun(T t);
it will create a template class T which can be
used as a type with functions.
Example for Funtion Template
#include<iostream.h>
template <class T>T Max(T a, T b)
{
if(a>b)
return a;
else
return b;
}
int main()
{
int a=10,b=20;
float c=10.34f,d=34.34f;
char e='A',f='a';
cout<<Max(a,b)<<endl<<Max(c,d)<<endl<<Max(e,f)<<endl;
return 0;
}
Explicitly Overloading a Generic Function
#include<iostream.h>
template <class X> void swapargs(X &a, X &b)
{
X temp;
temp = a;
a = b;
b = temp;
cout << "Inside template swapargs.\n";
}
void swapargs(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
cout << "Inside swapargs int specialization.\n";
}
Generic Function Restrictions
Generic functions are similar to overloaded functions except that they are more
restrictive.
When functions are overloaded, you may have different actions performed within
the body of each function.
But a generic function must perform the same general action for all versions—only
the type of data can differ.
Generic Classes
• In addition to generic functions, you can also define a generic
class.
• When you do this, you create a class that defines all the
algorithms used by that class,however, the actual type of the
data being manipulated will be specified as a parameter when
objects of that class are created.
• Generic classes are useful when a class uses logic that can be
generalized.
CLASS TEMPLATES
#include <iostream>
using namespace std;
template <class Type1, class Type2> class MyClass
{
Type1 i;
Type2 j;
public:
MyClass(Type1 a, Type2 b) { i = a; j = b; }
void show() { cout << i << ' ' << j << '\n'; }
};
int main()
{
MyClass<int, double> ob1(10, 0.23);
MyClass<char, char *> ob2('X', "Templates add power.");
ob1.show(); // show int, double
ob2.show(); // show char, char *
return 0;
}