Topic: Operator[] Sample


Author: fgothamNO@SPAM.com (Frederick Gotham)
Date: Fri, 28 Jul 2006 17:34:35 GMT
Raw View
I posted this a few hours ago and it hasn't shown up.

The code implements a wrapper for multi-dimensional arrays with index-
checking.

#include <cassert>
#include <cstdarg>

template<class T>
class Multi {
private:

    /* Singular-dimensional arrays are allowed. */

    Multi(Multi const&);  /* No definition anywhere */
    Multi &operator=(Multi const &);  /* No definition anywhere */

    unsigned const static max_dim = 16;

    unsigned const quantdim;

    unsigned dims[max_dim];
    unsigned const *const pdim_over;

    T *p;

    unsigned ProductOfSubsequentDimensions(unsigned const *pdim) const
    {
        assert(pdim);
        assert(pdim_over != pdim);

        unsigned product = 1;

        while(++pdim != pdim_over)
            product *= *pdim;

        return product;
    }

public:

    Multi(unsigned const arg_quant,unsigned const d1,...)
    : quantdim(arg_quant),pdim_over(dims + quantdim)
    {
        assert(arg_quant >= 1 && arg_quant <= 16);
        assert(d1);

        unsigned total_elem = d1;

        *dims = d1;  /* Set first dimension size */

        va_list ap;
        va_start(ap,d1);

        for(unsigned *pdim = dims + 1; pdim != pdim_over; ++pdim)
        {
            unsigned const i = va_arg(ap,unsigned);

            assert(i); /* Make sure not zero dimension */

            total_elem *= i;

            *pdim = i;
        }

        va_end(ap);

        p = new T[total_elem];
    }

    ~Multi() { delete [] p; }

    T &operator[](unsigned const d1,...)
    {
        /* Make sure first index is within range */
        assert(d1 < *dims); /* Or throw an exception */

        unsigned index = d1 * ProductOfSubsequentDimensions(dims);

        va_list ap;
        va_start(ap,d1);

        for(unsigned const *pdim = dims + 1; pdim_over != pdim; ++pdim)
        {
            unsigned const i = va_arg(ap,unsigned);

            assert(i < *pdim);  /* Or throw an exception */

            index += i * ProductOfSubsequentDimensions(pdim);
        }

        va_end(ap);

        return p[index];
    }
};

int main()
{
    Multi<int> arr(3,2,4,2);

        /* Not sure if I have to write 2U,4U,2U */

    arr[0][0][0] = 5;
    arr[0][0][1] = 46;
    arr[1][3][1] = -456;
}

--

Frederick Gotham

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]