Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement `opIndex` in higher dimensions?

Tags:

d

struct M{
 T opIndex(uint i){ ... }
}

which gives me this:

m[i]

but what if I want it in two dimension so that I could do:

m[i][j]

is there anyway to do this?

like image 882
Arlen Avatar asked Dec 20 '11 04:12

Arlen


1 Answers

Yes, you can do the C++ way of returning a temporary object (struct is best in D's case) which also has an index operator overload.

But a better idea in D is to go for the syntax m[i, j]:

struct S
{
    uint opIndex(uint i, uint j)
    {
        return i + j;
    }
}

void main()
{
    S s;
    assert(s[2, 3] == 5);
}

If you still want to use m[i][j], a nested struct gives you some syntactic leeway:

struct S
{
    auto opIndex(uint i)
    {
        struct Temp
        {
            uint opIndex(uint j)
            {
                return i + j;
            }
        }

        return Temp();
    }
}

void main()
{
    S s;
    assert(s[2][3] == 5);
}
like image 191
jA_cOp Avatar answered Nov 17 '22 22:11

jA_cOp