Templet class

Templet class:

Templates in C++ programming allows function or class to work on more than one data type at once without writing different codes for the different data types. Templates are often used in larger programs for the purpose of code reusability and flexibility of program.

Example 1:

#include<iostream.h>

template T<class T>

Large(T nn1, T nn2)

{

return (nn1>nn2) ? nn1:nn2;

}

int main()

{

int ii1, ii2; float ff1, ff2; char cc1, cc2;

cout<<“Type two integers nos are: “;

cin>>ii1>>ii2;

cout<<Large(ii1, ii2)<<” is larger.”;

cout<<“\n\nEnter two floating-point numbers: “;

cin>>ff1>>ff2;

cout<<Large(ff1, ff2)<<” is larger.”;

cout<<“\n\nEnter two characters: “;

cin>>cc1>>cc2;

cout<<Large(cc1, cc2)<<” has larger ASCII value.”;

return 0;

}

Output:
Type two integers nos are:78

66

78 is larger

Enter two floating-point numbers:6.9

7.9

7.9 is larger

Enter two characters:d

g

g has larger ASCII value.

Example2:

#include<iostream.h>

// class template declaration part

template<class any_data_type1>  class Test

{

public: Test();

~Test(); // method any_data_type1 Data(any_data_type1);

};

template any_data_type Test1::Data(any_data_type1 Var0)

{

return Var0;

}

template Test::Test()

{

cout<<“Constructor,is allocated now…”<<endl;

}

// destructor template

Test::~Test()

{

cout<<“Destructor,is deallocated now…”<<endl;

}

int main(void)

{

Test Varb1;

Test Varb2;

Test Varb3;

Test<char*> Varb4; cout<<“\nOne template fits all data type…”<<endl;

cout<<“Varb1, int = “<<Varb1.Data(800)<<endl;

cout<<“Varb2, double = “<<Varb2.Data(1.234)<<endl;

cout<<“Varb3, char = “<<Varb3.Data(‘K’)<<endl;

cout<<“Varb4, char* = “<<Varb4.Data(“The template class”)<<endl<<endl;

return 0;

}

Output :
Constructor,is allocated now…

Constructor, is allocated now…

Constructor, is allocated now…

Constructor, is allocated now…

One template fits all data type…

Var1, int = 800

Var2, double = 1.234

Var3, char = K

Var4, char* = The template class

Destructor, is deallocated…

Destructor, is deallocated now….

Destructor, is deallocated now…

Destructor, is deallocated now…

 

Leave a Reply

Your email address will not be published. Required fields are marked *