20121020

How to use template in cpp

How to use template in C++:
Template is mechanism in C++ to generate fanily of
 generic classes and generic functions that works with
different types of data types hence eliminate duplicate
 program for diffrent 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;

}



Previous                             Home                               Next

No comments:

Post a Comment