#include <stdio.h>

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(T in) : p(0), init(in), size(0) {}
    ~Array() { if (p) delete[] p; }
    T& operator[](unsigned int idx) {
        if (idx >= size)
            Resize(idx);
        return p[idx];
    }
    const T& operator[](unsigned int idx) const {
        return idx >= size ? init : p[idx];
    }
    unsigned int Size() const { return size; }
private:
    void 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];
        for (unsigned int i = 0; i < new_size; i++)
            new_array[i] = i < size ? p[i] : init;
        if (p)
            delete[] p;
        p = new_array;
        size = new_size;
    }
    void operator=(const Array<T>& ref) {}
    Array(const Array<T>& ref) {}
};

template <class T, T init_val, int dim>
class MultiMatrix {
    typedef MultiMatrix<T, init_val, dim-1> Sub;
    Array<Sub*> arr;
public:
    MultiMatrix() : arr(0) {}
    ~MultiMatrix() {
        for (unsigned int i = 0; i < arr.Size(); i++)
            delete arr[i];
    }
    Sub& operator[](unsigned int idx) {
        if (!arr[idx])
            arr[idx] = new Sub;
        return *arr[idx];
    }
    const Sub& operator[](unsigned int idx) const {
        static Sub dummy;
        return arr[idx] ? *arr[idx] : dummy;
    }
};

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;
    m[0][0][0] = 1;
    m[0][0][20] = 2;
    m[0][5][3] = 3;
    m[9][0][0] = 4;
    printf("%d %d %d %d\n", m[0][0][0], m[0][0][20], m[0][5][3], m[9][0][0]);
    printf("%d %d\n", c[4][4][4], m[4][4][4]);
    return 0;
}
