Showing posts with label Template. Show all posts
Showing posts with label Template. Show all posts

Template Method and template class example in C++ Linux

How to use template in C++:
Template is mechanism in C++ to generate family of
 generic classes and generic functions that works with
different types of data types hence eliminate duplicate
 program for different data types and make the program
 more manageable and easier.
C++ Program for 1 argument template class
#include<iostream.h>
#include<string.h>
template <class T>
class test
{
T t;
public:
test(T x)//will work with int, float,char,string
{
t=x;
}
 void show(void)
 {
  cout<<"t= "<<t<<endl;
 }
};
//void test< T>::show(void)
//{
//cout<<"t"<<t<<endl;
//}
int main()
{
test<int>t1(10); //calls int version of test(T t)
t1.show();
test<float>t2(1.0);  //calls float version of test(T t)
t2.show();
test<char>t3('m');   //calls char version of test(T t)
t3.show();
test<char *>t4("HelloTemplate"); // calls string version of test(T t)
t4.show();
return 0;
}
C++ Program for 1 argument template function

#include<iostream.h>
//using namespace std
template <class T>
void display(T a)
{
cout<<a<<endl;
}
int main()
{
display(10);
display(20.12);
display('M');
display("MamaMeaa");
return 0;

}
 
//Template method example
#include<iostream>
using namespace std;
template<typename T1, typename T2>
void add(T1 a, T2 b)
{
    cout<<"\nSum : "<<a+b<<endl;
}

template<typename T3, typename T4>
T3 addSameAndReturn(T3 a, T4 b)//T1 T1
{
return a+b;
}
int main ()
{
    add(4,5.5454);//9.5454
    //specify types while passing values to funcion
    add<int,double>(4,5.5454);//9.5454
    add<float,int>(4.7,5); //9.7
    add<string,string>("hi","bye");//hibye

cout<<"addSameAndReturn(10.2,10.3)="<<addSameAndReturn(10.2,10.3)<<endl;//20.5
cout<<"addSameAndReturn(10,10.3)="<<addSameAndReturn<int,float>(10,10.3)<<endl;//20
cout<<"addSameAndReturn(10,10.3)="<<addSameAndReturn<float,int>(10.3,10)<<endl;//20.3

    return 0;
}