template class with type parameter : template class « Class « C++






template class with type parameter

  
#include <iostream>
#include <stdlib.h>
using namespace std;
const int SIZE = 10;

template <class T> class MyClass {
   T a[SIZE];
 public:
   MyClass(void)
    {
      int i;

      for(i=0; i<SIZE; i++)
         a[i] = i;
    }
   T &operator[](int i);
};

template <class T> T &MyClass<T>::operator[](int i)
{
   if(i<0 || i> SIZE-1)
    {
      cout << endl << "Index value of ";
      cout << i << " is out of bounds." << endl;
    }
   return a[i];
}

int main(void)
{
   MyClass<int> int_array;
   MyClass<double> double_array;
   int i;

   cout << "Integer array: ";
   for(i=0; i<SIZE; i++)
      int_array[i] = i;
   for(i=0; i<SIZE; i++)
      cout << int_array[i] << " ";
   cout << endl;

   cout << "Double array: ";
   cout.precision(2);
   for(i=0; i<SIZE; i++)
      double_array[i] = (double)i/3;
   for(i=0; i<SIZE; i++)
      cout << double_array[i] << " ";
   cout << endl;

   int_array[12] = 100;                 // Calls overloaded array operator
}
  
    
  








Related examples in the same category

1.template class with generic parameter
2.Demonstrate a very simple safe pointer class.
3.A generic safe-array class that prevents array boundary errors.
4.Get storage off stack for array
5.template extending
6.sequence template
7.Template Version of Generic binary sorted Tree.
8.template class with two generic parameters
9.generic stack template class
10.Using exceptions with templates.
11.Passing by reference and using virtual functions in exceptions.
12.Using Non-Type Arguments with Generic Classes
13.Using Default Arguments with Template Classes
14.Generic Classes: demonstrates a generic stack.
15.An Example with Two Generic Data Types
16.Applying Template Classes: A Generic Array Class
17.Explicit Class Specializations for generic template class