Using Non-Type Arguments with Generic Classes : template class « Class « C++

Using Non-Type Arguments with Generic Classes

#include <iostream>
#include <cstdlib>
using namespace std;
template <class T, int size> class MyClass {
  T a[size]; // length of array is passed in size
  MyClass() {
    register int i;
    for(i=0; i<size; i++) a[i] = i;
  T &operator[](int i);
template <class T, int size>
T &MyClass<T, size>::operator[](int i)
  if(i<0 || i> size-1) {
    cout << i << " is out-of-bounds.\n";
  return a[i];
int main()
  MyClass<int, 10> intob;       
  MyClass<double, 15> doubleob; 
  for(int i=0; i<10; i++) 
     intob[i] = i;
  for(int i=0; i<10; i++) 
     cout << intob[i] << endl;
  for(int i=0; i<15; i++) 
     doubleob[i] = (double) i/3;
  for(int i=0; i<15; i++) 
     cout << doubleob[i] << "  ";
  return 0;

Related examples in the same category

1.template class with type parameter
2.template class with generic parameter
3.Demonstrate a very simple safe pointer class.
4.A generic safe-array class that prevents array boundary errors.
5.Get storage off stack for array
6.template extending
7.sequence template
8.Template Version of Generic binary sorted Tree.
9.template class with two generic parameters
10.generic stack template class
11.Using exceptions with templates.
12.Passing by reference and using virtual functions in exceptions.
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