Templates in C++ Part – 1
Master C++ with Real-time Projects and Kickstart Your Career Start Now!!
Program 1
// template in C++
#include<iostream>
using namespace std;
template<class T>
class Test
{
T n; //string n
public:
Test(T m) //string m
{
n=m;
}
void show()
{
cout<<"Value is: "<<n<<endl;
}
};
int main()
{
system("cls");
Test<int> T1(500);
Test<string>T2("DataFlair");
Test<double>T3(90.123);
Test<char>T4('Z');
T1.show();
T2.show();
T3.show();
T4.show();
return 0;
}
Program 2
// template in C++
#include<iostream>
using namespace std;
template<class T,class V>
class Test
{
T x;
V y;
public:
Test(T a, V b)
{
x=a;
y=b;
}
void show()
{
cout<<" First value: "<<x<<endl;
cout<<" Second value: "<<y<<endl;
}
};
int main()
{
system("cls");
Test<int,double>T1(123,56.77);
Test<string,int> T2("Vivek",127);
Test<float,string> T3(123.55,"Dataflair");
T1.show();
T2.show();
T3.show();
return 0;
}Program 3
// function template in C++
#include<iostream>
using namespace std;
template<typename T>
void display( T m) //int , string , double
{
cout<<"value is: "<<m<<endl;
}
int main()
{
system("cls");
display(100); //int
display("Hello"); //string
display(123.56); //double
return 0;
}Program 4
// function template in C++
#include<iostream>
using namespace std;
template<typename T>
void swapvalue(T &a,T &b)
{
T c;
c=a;
a=b;
b=c;
}
int main()
{
system("cls");
int x=500,y=200;
cout<<"\nBefore swaping: "<<x <<" "<<y<<endl;
swapvalue(x,y);
cout<<"After swaping: "<<x <<" "<<y;
cout<<"\n---------------------------------------------------------"<<endl;
double a=50.34,b=20.66;
cout<<"\nBefore swaping: "<<a <<" "<<b<<endl;
swapvalue(a,b);
cout<<"After swaping: "<<a <<" "<<b;
cout<<"\n---------------------------------------------------------"<<endl;
string m="Hello",n="Friends";
cout<<"\nBefore swaping: "<<m <<" "<<n<<endl;
swapvalue(m,n);
cout<<"After swaping: "<<m <<" "<<n;
return 0;
} Your opinion matters
Please write your valuable feedback about DataFlair on Google

