Page 314 - DCAP404 _Object Oriented Programming
P. 314

Unit 14: Advanced Concept in C++




                         W  < int , 10 > + twoptr = & one ;    // No object is created          Notes
                         W  < int, 10 + 3 > three = 200;         // Displays a = 230
                         W  < float, 40 > four = 100.45 ;       // Displays  a = 140.45
                         Return  0;
                 }

          Rules for Using Templates

          Listed below are the rules for using templates:
          1.   The name of a parameter can appear only once within a formal parameter list. For example:
                 Template    <class  type>
                 Type  max  (  type  a,  type  b)

                 {
                         return a  > b ?  a :  b ;
                 }
          2.   The keyword, class must be specified before the identifier.
          3.   Each of the formal  parameters should form a part of the signature of the function. For
               example:

                 Template  <  class  T  >
                 Void  func  (  T  a  )
                 {
                 ......
                 }
          4.   Templates cannot be  used for all overloaded functions. They can be used only for those
               functions whose function body is the same and  argument types are different.

          5.   A built-in data type is not to be given as a template argument in the list for a template
               function but the function may be called with  it. For example:
                 Template  <  class    ZZ    ,  int  >      //    wrong

                 Void  fn  (  ZZ  ,  int)  ;
                 Template < class Z >             //  right
                 Void  fn  (  ZZ  ,  int  )  ;
          6.   Template arguments can take default values. The value of these arguments become constant
               for that particular instantiation of the template.


                 Example:
                 Template    <  class  X  ,  int  var  =  69  >
                 Class  Aclass
                 {
                         public  :

                         void  func    (  )



                                           LOVELY PROFESSIONAL UNIVERSITY                                   307
   309   310   311   312   313   314   315   316   317   318   319