***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Saturday, July 24, 2021

Class Templates

Templates may also be used to create generic classes and abstract data types. Class templates allow you to create one general version of a class without having to duplicate code to handle multiple data types. 

Declaring a class template is very similar to declaring a function template. First, a template prefix, such as template<class T>, is placed before the class declaration. As with function templates, T (or identifier choose to use) is a data type parameter. Then, throughout the class declaration, the data type parameter is used where you wish to support any data type.

Example:

template <class T>

class MyTemplate {

T element;

public:

MyTemplate (T arg)

{element=arg;}

T divideBy2 ()

{return element/2;}

};

void main()

{

MyTemplate<int> obj(10);

obj.divideBy2();

}

 

To declare an object of this class to store integer values of type int we would write:

 

MyTemplate<int> obj;

No comments:

Post a Comment