Kamis, 31 Maret 2011

Declaring C++ Class Templates

           Declaration of C++ class template should start with the keyword template. A parameter should be included inside angular brackets. The parameter inside the angular brackets, can be either the keyword class or typename. This is followed by the class body declaration with the member data and member functions. The following is the declaration for a sample Queue class.

//Sample code snippet for C++ Class Template
template <typename T>
class MyQueue
{
         std::vector<T> data;
      public:
         void Add(T const &d);
         void Remove();
         void Print();
};

   The keyword class highlighted in blue color, is not related to the typename. This is a mandatory keyword to be included for declaring a template class.

Defining member functions - C++ Class Templates:

   If the functions are defined outside the template class body, they should always be defined with the full template definition. Other conventions of writing the function in C++ class templates are the same as writing normal c++ functions.
template <typename T> void MyQueue<T> ::Add(T const &d)
{
     data.push_back(d);
}
template <typename T> void MyQueue<T>::Remove()
{
      data.erase(data.begin( ) + 0,data.begin( ) + 1);
}
template <typename T> void MyQueue<T>::Print()
{
     std::vector <int>::iterator It1;
     It1 = data.begin();
     for ( It1 = data.begin( ) ; It1 != data.end( ) ; It1++ )
          cout << " " << *It1<<endl;

}
 

   The Add function adds the data to the end of the vector. The remove function removes the first element. These functionalities make this C++ class Template behave like a normal Queue. The print function prints all the data using the iterator.

Full Program - C++ Class Templates:

//C++_Class_Templates.cpp

#include <iostream.h>
#include <vector>

template <typename T>
class MyQueue
{
     std::vector<T> data;
   public:
     void Add(T const &);
     void Remove();
     void Print();
};
template <typename T> void MyQueue<T> ::Add(T const &d)
{
     data.push_back(d);
}
template <typename T> void MyQueue<T>::Remove()
{
     data.erase(data.begin( ) + 0,data.begin( ) + 1);
}
template <typename T> void MyQueue<T>::Print()
{
     std::vector <int>::iterator It1;
     It1 = data.begin();
     for ( It1 = data.begin( ) ; It1 != data.end( ) ; It1++ )
        cout << " " << *It1<<endl;
}
//Usage for C++ class templates
void main()
{
     MyQueue<int> q;
     q.Add(1);
     q.Add(2);

     cout<<"Before removing data"<<endl;
     q.Print();

     q.Remove();
     cout<<"After removing data"<<endl;
     q.Print();
}


Tidak ada komentar:

Posting Komentar