Monday, April 20, 2009

Class Template

Consider a vector class defined as follows:
Now suppose we want to define a vector that can store angry of float values. We van do this by simply replacing the appropriate int declaration with float in the vector class. This means that we have to redefine the entire class all over again.
Assume that we want to define a vector class with the data type as a parameter and then use this class to create a vector of any data type instead of defining a new class every time. The template mechanism enables us to achieve this goal.
As mentioned earlier, templates allow us to define generic classes. It is a simple process to create a generic class suing a template with an anonymous type. The general format of a class template is:

Template <>
Class clase_name
{
// Class member specification
// With anonymous type T
// Wherever appropriate


};

The template definition of vector class shown below illustrates the syntax of a template:
Note that the class template definition is very similar to an ordinary class definition except the prefix template <> and the use of type T. This prefix tells the compiler that we are going to declare a template and use as a type name in the declaration. Thus, vector has become a parameterized class with the type T as its parameter. T may be substituted by any data type including the user-defined types now, we can curare vectors for holding different data types.

Example:

Vector <> v1 (10); // element int vector
Vector <> v3(25); 25 element float vector
Note that the type T may represent a class name as well.

Example:
Vector <> v3(5); // vector if 5 complex numbers

A class created from a class template is called a template class. The syntax for defining an object of a template classis:
Class_name <> object_name (arg list);
This process of creating a specific class form a class template is called instantiation. The compiler will perform the error analysis only when an instantiation takes place. It is, therefore, advisable to create and debug an ordinary class before converting it into a template.

No comments:

Post a Comment