Wednesday, 26 June 2013

What is template in c++

Templates is one of the most striking feature added in the c++. It is a new concept which enables us to define Generic classes and functions and thus provides support for generic programming
Generic programming is an approach where genreric types are used as parameters in the algorithms
so that they work for variety of suitable data type and data structure .

A template can used to create a family of classes or functions
For Example
 
     template<class T>
     class  ClassName
     {
               

      };

    the above is the skelton of the  template class
  
  template <class T>
 class vector
 {
       T* v;
       public :
          vector()
           {
                v  = new T[size];
               
                for(int i =0; i < size; i++)
                        v[i] = 0;
          }  
         
       vector(T* a)
        {
               for(int i =0; i <SIZE; i++)
                      v[i] = a[i];
        }
     
       T operator*(vector &y)
       {
               T sum =0;
             
                for(int i =0;  i <size; i++)
                        sum += this->v[i] * y.v[i];
               return sum;
      }
};

int main()
{
         int x[4] = {1, 2, 3, 4};
         int y[4]  = {4, 5, 6,7};
        
        vector<int> v1;
        vector<int> v2;
           
       v1 = x;
       v2 = y;
 
       int R = v1 * v2;
 
       cout << "R = " <<R ;
      return 0;  
}



           

                            

     
       






0 comments:

Post a Comment