Should opIndex completely override alias this?

kenji hara k.hara.pg at gmail.com
Fri May 11 10:31:59 PDT 2012


2012/5/12 Mehrdad <wfunction at hotmail.com>:
> On Friday, 11 May 2012 at 17:19:28 UTC, kenji hara wrote:
>>
>> This is expected behavior.
>>
>> 'alias this' works as proper super type.
>>
>> struct S { T[] data; alias data this; }
>>
>> In this code, S behaves as it is derived from T[] .
>>
>> Following to this view, the definition of opIndex in S overrides (and
>> hides) T[]'s opIndex completely.
>>
>> Kenji Hara
>
>
> How do you overcome this, in the case where you don't know the data type of
> 'data' (so you don't know what the overloads might look like, maybe because
> it's a template)?

I'll add 'forwarding opIndex'.

struct S(T)
{
    T data;
    alias data this;

    int opIndex()(size_t i, size_t j)
    {
        return 100; // specialized opIndex
    }
    auto opIndex(A...)(A args) if (A.length != 2)
    {
        return data[args];  // forwarding
    }
}
void main()
{
    auto s = S!(int[])([1,2]);
    assert(s[1,2] == 100);
    assert(s[0] == 1);
    assert(s[1] == 2);
}


More information about the Digitalmars-d mailing list