Simulating rectangular array

Philippe Sigaud philippe.sigaud at gmail.com
Sun Jun 17 13:24:49 PDT 2012


On Sun, Jun 17, 2012 at 9:50 PM, Andrej Mitrovic
<andrej.mitrovich at gmail.com> wrote:
> Has anyone come up with a template that can simulate a rectangular
> array and allow one to override opAssign to do special work? E.g.:
>
> Array!(2, 4) arr;
> arr[1][3] = "foo";
>
> This would invoke opAssign in some templated struct "Array". This
> would be super-easy to implement if I had an opIndex that could work
> with the above syntax. I know there's a "[1, 3]" syntax but I really
> need the array "[1][3]" syntax.
>
> Maybe Philippe has this in his templates book? (If not it would be a
> great addition to it)

No, I don't have something like this. Sorry if the question is stupid,
but how is your Array!(n,m) any different from string[n][m]?

And yes, Jonathan's idea is how I'd do it:

module test;

import std.conv;
import std.stdio;

class Array(T, size_t n,size_t m)
{
    T[n*m] payload;

    this(T[n*m] _payload) { payload = _payload;}

    Indexer opIndex(size_t i)
    {
        assert(i < n);
        return new Indexer(i);
    }

    class Indexer
    {
        size_t i;
        this(size_t _i) { i = _i;}

        auto opIndex(size_t j)
        {
            assert(j < m);
            return payload[i*m+j];
        }
    }
}

void main()
{
    auto arr = new Array!(string, 2,4)(["abc", "def", "ghi", "jkl",
"mno", "pqr", "stu", "vwx"]);
    writeln(arr[1][0]);
}

I guess this can extended to a general, N-dimensional, 'arrays'
(tensor, right?).


More information about the Digitalmars-d-learn mailing list