opIndex negative index?

cerjones who at what.com
Thu Jan 21 14:47:38 UTC 2021


On Thursday, 21 January 2021 at 14:25:41 UTC, IGotD- wrote:
> On Thursday, 21 January 2021 at 14:00:28 UTC, cerjones wrote:
>
> Not possible, indexes are of type size_t which is unsigned. If 
> you want negative indexes you need to wrap arrays in your own 
> implementation and offset 0 so that negative indexes can be 
> used.

import std;

struct Foo
{
     int opIndex(int idx)
     {
         return idx;
     }
}

void main()
{
     Foo foo;
     writeln(foo[-1]);
}

prints:

-1

And just for weirdness...

import std;

struct Foo
{
     string opIndex(string s)
     {
         return s;
     }
}

void main()
{
     Foo foo;
     writeln(foo["ohrealy?"]);
}

prints:

ohreally?


More information about the Digitalmars-d-learn mailing list