#include <stdio.h>

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(const T& in) : p(0), init(in), size(0) {}
    Array(const Array<T>& other);               /* allowed again */
    ~Array() { delete[] p; }
    Array<T>& operator=(const Array<T>& other); /* allowed again */
    T& operator[](unsigned int idx);
    const T& operator[](unsigned int idx) const;
    unsigned int Size() const { return size; }
private:
    void Resize(unsigned int required_index);
};

template <class T>
Array<T>::Array(const Array<T>& other) : p(0), init(other.init), size(0)
{
    *this = other;
}

/* a deep copy: every element is assigned, and an element may be a matrix */
template <class T>
Array<T>& Array<T>::operator=(const Array<T>& other)
{
    if (this == &other)
        return *this;
    T *copy = other.size ? new T[other.size] : 0;
    for (unsigned int i = 0; i < other.size; i++)
        copy[i] = other.p[i];
    delete[] p;
    p = copy;
    init = other.init;
    size = other.size;
    return *this;
}

template <class T>
T& Array<T>::operator[](unsigned int idx)
{
    if (idx >= size)
        Resize(idx);
    return p[idx];
}

template <class T>
const T& Array<T>::operator[](unsigned int idx) const
{
    return idx >= size ? init : p[idx];
}

template <class T>
void Array<T>::Resize(unsigned int required_index)
{
    unsigned int new_size = size == 0 ? 8 : size;
    while (new_size <= required_index)
        new_size *= 2;
    T *new_array = new T[new_size];             /* default constructor */
    for (unsigned int i = 0; i < new_size; i++)
        new_array[i] = i < size ? p[i] : init;  /* assignment */
    delete[] p;
    p = new_array;
    size = new_size;
}

template <class T, T init_val, int dim>
class MultiMatrix {
    Array<MultiMatrix<T, init_val, dim-1> > arr;
public:
    MultiMatrix() : arr(MultiMatrix<T, init_val, dim-1>()) {}
    MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx)
        { return arr[idx]; }
    const MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx) const
        { return arr[idx]; }
};

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
};

int main()
{
    MultiMatrix<int, -1, 3> m;
    const MultiMatrix<int, -1, 3>& c = m;

    for (int j = 0; j < 1000; j++)
        m[0][j][0] = j;                 /* 1000 rows inside m[0] */
    m[8][0][0] = 5;                     /* the top level grows: 8 -> 16 */
    printf("%d %d %d %d\n", c[0][0][0], c[0][999][0], c[8][0][0],
           c[3][3][3]);
    return 0;
}
