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

Templates  are  also  called  'generics'  or  'parameterized  types'.  Programming  with templates  is  called  generic  programming.


In  general,  study  of  templates  can  be  divided  in  two  parts.

1)  Function  templates
2)  Class  templates



Function  Templates

Function  templates  enable  us  to  construct  a  family  of  related  functions.  Suppose  we want  to  have  function add ( ),  which  adds  two  numbers.  C++  is  strongly  typed.  Hence if we  define  add ( int,  int )  it  will  not  work  properly  for  floats  or  complex  numbers. Here the  concept  of  template  can  be  brought  in.  We  will  define  function  add   to  have parameters  of  type  T,  where  T  is  template  type.



For  Example,

template  < class  T >
void  add ( T  a,  T  b ) ;



The  first  line  tells  the  compiler  that  we  are  using  a  generic  type T.  Once  T  is accepted  as  some  type,  declaration  of  the  function  is  logical.  While  defining  the function,  syntax  of  C++  requires  us  to  add  template < class  T >  before  the  function definition.  Now  a  function  add ( )  can  be  called  with  parameters  of  any  type.



Let  us  study  a  simple  program  to  study  function  templates.



                                   #include < iostream.h >
                                   template < class  T >
                                   void  add ( T  a,  T  b ) ;
                                   int  main ( )
                                   {
                                              int  a = 5,  b = 7 ;
                                              add ( a,  b ) ;
                                              float  x = 1.5,  y = 2.4 ;
                                              add ( x,  y ) ;
                                              return  0 ;
                                   }



                                 template  < class  T >
                                 void  add ( T  a,  T  b )
                                 {
                                       cout  << a + b  <<"\n" ;
                                 }



output

12
3.9