Template: – A significant benefit of object oriented programming is reusability of code which elements redundant coding. An important feature of C++ called templates strengths this benefits of Object oriented programming (OOP) and provide grate flexibility to the language. Template support generic programming, which allows to develop reusable software components such as function, class, etc., supporting different data types can be developed.

A template in C++ allows the constructor of a family of template function and classes to perform the same operation of different data type. A template can be divided into two different categories called function template and class template. A template declared for function are called function template and those are declared for classes are called class template. They perform appropriate operation depending on the data type of the parameter past to them.

Function template: – There are several function of considerable importance which have to be used frequently with different data type. The limitation of such function is that they operate only on a particular data type. It can be overcome by defining that function as a function template or generic function. A C++ function template is normally designed to handle specific data type. Offend, they are functionality make sense conceptually with other data type. A function template specifies how and individual function can be constructed.

Syntax of function template: – A function template is predefine with a keyword template and a list of complete type argument. These complete type arguments are called generic data type, since there exact representation is not known in the declaration of the function templates it is known only at the point of a call to a function template. The syntax of function template is –

Template <class T,_ _ _>
ReturnType FuncName(Arguments)
{
                                _ _ _ _ _
                                // Body of template function
                                _ _ _ _ _
}

Class template: – A similar to function template, class template can also be declared to object on different data type. When template used in a class is called class template. A class template specifies how individual classes can be constructed similar to normal class specification. These classes model a generic classes which support similar operation for different data type. A generic stack class can be created, which can be used for storing data of type integer, real, character, etc.

The syntax of declaring class template and defining object and its data members is – 

Template <class T1,class T2, _ _ _ _ _ >
Class <Class Name>
{
                T1 data;
                <Return Type> <Function Name>(Argument)
                {
                                //Body
                }
};

 

Advertisements