A keyword “template” in C++ is used for the template’s syntax and angled bracket in a parameter (t),
which defines the data type variable.
Class Template:
A class template starts with the keyword template followed by template parameter(s) inside <> which
is followed by the class declaration
#include<iostream>
using namespace std;
template< class T >
class num
{
public:
T number;
num ( T n )
{
number = n;
}
T returnnum()
{
return number;
}
};
int main()
{
num < int > obj1( 5 );
cout << " Int = "<< obj1.returnnum();
num < float > obj2( 2.3 );
cout << " Float = " << obj2.returnnum();
}
Output:
Int = 5
Float = 2.3
Making a Simple Calculator using a class template:
#include<iostream>
using namespace std;
template <class T>
class calc
{
T n,m;
public:
calc(T n1,T n2)
{
n=n1;
m=n2;
}
T sub()
{
return n-m;
}
T mul()
{
return n*m;
}
T divv()
{
return n/m;
}
T add()
{
return n+m;
}
void disp()
{
cout<<"add = "<<add()<<endl;
cout<<"sub = "<<sub()<<endl;
cout<<"mul = "<<mul()<<endl;
cout<<"div = "<<divv()<<endl;
}
};
int main()
{
calc < int > obj(10,5);
obj.disp();
}
Output:
add = 15
sub = 5
mul = 50
div = 2
Function Template:
A function template starts with the keyword template followed by template parameter(s)
inside <> which is followed by the function definition.
#include<iostream>
using namespace std;
template < typename T >
T add ( T n1 , T n2 )
{
return n1 + n2;
}
int main()
{
int r1;
float r2;
r1 = add < int > ( 1 , 2 );
cout << " int addition " << r1 << endl;
r2 = add < float > ( 1.1 , 2.2 );
cout << " float addition " << r2 << endl;
}
Output:
int addition 3
float addition 3.3
Swapping numbers using function template
#include < iostream >
using namespace std;
template < typename T >
void swap ( T n1 , T n2 )
{
cout << " Nos before swapping are: " << endl;
cout << " n1 = " << n1 << " , n2 = " << n2 << endl;
T temp;
temp = n1;
n1 = n2;
n2 = temp;
cout << " Nos after swapping are: " << endl;
cout << " n1 = " << n1 << " , n2 = " << n2 << endl;
}
int main()
{
swap < int > ( 2 , 3 );
swap < float > ( 2.2 , 3.3 );
}
Output:
Nos before swapping are: n1 = 2 , n2 = 3
Nos before swapping are: n1 = 3 , n2 = 2
Nos before swapping are: n1 = 2.2 , n2 = 3.3
Nos before swapping are: n1 = 3.3 , n2 = 2.2
0 Comments