Coupon Accepted Successfully!


Guidelines For Templates

  1. Templates are applicable when we want to create a type secure class that can handle different data types with similar member functions.
  2. The template classes can also be involved in inheritance. For example,

template<class T>

class data : public base<T>

Both data and base are template classes. The class data are derived from the template class base.
  1. The template variables also allow us to assign default values. For example,

template <class T, int x = 20>

class data


T num[x];


  1. The name of the template class is written differently in various situations. When it is a class declaration, it is declared in the following manner:
    class data {};
    For member functions, the declaration is as follows:

void data <T>:: show (T d) {}

where show() is a member function.

Finally, while declaring objects, the class name and specific data are specified before the object name.

data <int> i1 // Object of class data supports integer values

data <float> f1 // Object of class data supports float values

  1. All template arguments declared in the template argument list should be used for the definition of formal arguments. If one of the template arguments is not used, the template will be specious. Consider the following example:

template < class T>

T show (void)


return x;


In the above example, the template argument T is not used as a parameter, and the compiler will report an error.

template<class T>

void show (int y)


T tmp;


In the above example, the template-type argument is not used as an argument. The system will probably crash.

template <class T, class S>

void max ( T & k)


S p;


The template variable S is not used. Therefore, compile time error is generated.

Test Your Skills Now!
Take a Quiz now
Reviewer Name