Can opDollar support a jagged 2D array?

Steven Schveighoffer schveiguy at gmail.com
Fri Oct 2 13:32:22 UTC 2020


On 10/1/20 10:34 PM, James Blachly wrote:
> Suppose I have a data structure encoding sequence lengths:
> 
> seq1: 0 1 2 ... N
> seq2: 0 1 2 3 4 ... M
> seq3: 0 1 ... P
> 
> I would like to write opIndex and opDollar to support the notation 
> obj[seq, x .. $] to retrieve sequences.
> 
> However, given that opDollar is templated on dimension (always 1 in this 
> example) and has no information calling function's context/dimension 0 
> parameter, this seems impossible.
> 
> Am I missing an easy solution?

This seems like an oversight. But it's not impossible.

Just curry the information to the receiver. opDollar doesn't have to 
return a size_t.

Something like:

struct FromEnd
{
   ptrdiff_t offset;
   FromEnd opBinary(string s, T)(T val)
   {
       mixin("return FromEnd(offset " ~ s ~ " val);");
   }
}

struct MyStructure
{
    FromEnd opDollar(size_t col)() if(col == 1) { return FromEnd.init; }
}

And then inside your opIndex, you have to handle that type specially 
according to context.

The saving grace here is that opDollar doesn't exist except in an 
indexing operation, so you don't need to worry about it except in that 
context. opDollar is really kind of a hacky way to do this. It was added 
back when multi-dimensional indexing was not yet solid.

-Steve


More information about the Digitalmars-d-learn mailing list