Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
Class  Templates

Templates   allow   us   to  define  generic  classes.  It  is  used  to  define  a  pattern  for class  definitions.  Alternatively  we  could  call  it  a  parameterized  class.  Here,  there will be  one  class  definition,  which  will  produce  many  classes  depending  on  the parameter we  specify  in  terms  of  template  definition.


The  general  format  of  a  class  template  is :


                                   template < class  T >
                                   class  classname
                                   {
                                              // . . .
                                              //  class  member  specification
                                              //  with  type  T whereever  appropriate
                                              // . . .
                                   } ;



Note  that  the  class  template  definition  is  very  similar  to  an  ordinary  class  definition except  the  prefix  template  < class  T >  and  the  use  of  type  T.  This  prefix  tells  the   compiler  that  we  are  going  to  declare  a  template  and  use  T  as  a  type  name  in  the declaration.

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.



                       template < class  T >
                       class  vector
                       {
                                   T   a [ 10 ] ;
                                   public :
                                               // . . .
                                               // . . .
                       } ;



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 create  vectors  for  holding  different  data  types.


For  Example,


                      vector  < int >   object1 ;      //  10  element  int  vector
                      vector  < float >   object2 ;   //  10  element  float  vector