Wednesday, November 30, 2011

C++ Tutorial: Class Templates

We also have the possibility to write class templates, so that a class can have members that use template parameters as types. For example:
template <class T>
class mypair {
    T values [2];
  public:
    mypair (T first, T second)
    {
      values[0]=first; values[1]=second;
    }
};

The class that we have just defined serves to store two elements of any valid type. For example, if we wanted to declare an object of this class to store two integer values of type int with the values 115 and 36 we would write:

mypair<int> myobject (115, 36); 

this same class would also be used to create an object to store any other type:

mypair<double> myfloats (3.0, 2.18); 

The following example further illustrates the concept of class templates. Here class Stack is a template class so it can be used for various data types like int, float , char etc.
#include<iostream>
using namespace std;

const int MAX = 20;
template <class T>
class Stack
{
    private:
        T arr[MAX];
        int top;
    public:
        Stack();
        void push(T data);
        T pop();
        int size();
};
template <class T>
Stack<T>::Stack()
{
    top =-1;
}

template <class T>
void Stack<T>::push(T data){
    arr[++top] = data;}

template <class T>
T Stack<T>::pop()
{
    return arr[top --];
}

template <class T>
int Stack<T>::size()
{
    return (top +1);
}

int main()
{
    cout<<"Stack for integer data type "<<endl;
    Stack <int>s1;
    cout<<"Size of stack "<<s1.size()<<endl;
    s1.push(11);
    s1.push(22);
    s1.push(44);

    cout<<"Size of stack: "<<s1.size()<<endl;
    cout<<"Number Popped: "<<s1.pop()<<endl;

    cout<<"Size of Stack: "<<s1.size()<<endl;
    return 0;
}





No comments:

Post a Comment