$, __dollar, opDollar: can't define my own?

Oskar Linde oskar.lindeREM at OVEgmail.com
Tue Oct 3 02:14:48 PDT 2006


Chris Miller wrote:
> There should be an opDollar, or some other name, such as opEnd, to 
> overload $ for user-defined classes/structs/unions. Or instead, it could 
> even simply just access a length member if it exists.
> 
> I have a struct that wraps an array and works like an array in almost 
> every way except for the $ feature of arrays.

It would also be very nice to support $ in some way for multidimensional 
indexing:

myclass[$-1, $-1]

myclass[1..$-1, x % $]

For some of my own classes, I have a templated opIndex that supports:

myclass[end-1,end-1]

myclass[range(1,end-1), x % end]

etc...

It would be really nice to get the same functionality with the first syntax.

My solution is to make special types. Briefly:

struct End {
   EndRel opMinus(int i) { EndRel x = {i}; return x; }
   EndMod opMod_r(int i) { EndMod x = {i}; return x; }
}

End end; // Global end instance

struct EndRel { int i; }
struct EndMod { int i; }

struct FullRange {}

Fullrange all; // Global all range

struct Range {
   int start, end;
}

struct EndRange {
   int start;
}

struct EndRelRange {
   int start;
   int endrel;
}

Range range(int start, int end) { Range x = {start,end}; return x; }

EndRange range(int start, End dummy) { EndRange x = {start}; return x; }

EndRelRange range(int start, EndRel endrel) {
   EndRelRange x = {start,endrel};
   return x;
}

The class template code for opIndex then need to handle arguments of 
types int, End, EndRel, EndMod, FullRange, Range, EndRange, EndRelRange, 
etc...

This may all be a bit overkill, but what would be really great is having 
a range type that a..b expands into at lest. That type could then 
support opApply making

foreach(i; 0..10) { ... }

possible for instance.

/Oskar



More information about the Digitalmars-d mailing list