Type-Strict Indexes: IndexedBy

Tobias Pankrath via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 16 12:19:44 PST 2015


On Monday, 16 February 2015 at 20:09:09 UTC, Nordlöw wrote:
> I'm trying to figure out how to implement a light-weight wrappr 
> realizing type-safe indexing á lá Ada. Here's my first try:
>
> struct Ix(T = size_t)
> {
>     @safe pure: @nogc nothrow:
>     this(T ix) { this._ix = ix; }
>     alias _ix this;
>     private T _ix = 0;
> }
>
> struct IndexedBy(R, I)
> {
>     auto ref opIndex(I ix) inout { return _r[ix]; }
>     auto ref opSlice(I lower, I upper) inout { return _r[lower 
> .. upper]; }
>     R _r;
>     alias _r this;
> }
>
> auto indexedBy(I, R)(R range)
> {
>     return IndexedBy!(R, I)(range);
> }
>
> unittest
> {
>     import std.stdio;
>     auto x = [1, 2, 3];
>     alias I = int;
>     auto ix = x.indexedBy!I;
>     ix[0] = 11;
>
>     alias J = Ix!size_t;
>     auto jx = x.indexedBy!J;
>     jx[J(0)] = 11;              // should compile
>     jx[0] = 11;                 // TODO how can I make this not 
> compile?
> }
>
> My question now of course is:
>
> How can I prevent
>
>     jx[0] = 11;
>
> from compiling?

Did you actually try that? This does not compile because of c[13]

struct IndexT
{
         this(size_t s) { x = s; }
         size_t x;
}

struct Container
{
         int opIndex(IndexT i) { return 12; }
}

void main()
{
         auto it = IndexT(13);
         Container c;
         c[it];
         c[13];
}



More information about the Digitalmars-d-learn mailing list