opIndexDispatch?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Oct 12 18:09:06 PDT 2016


On 10/10/2016 12:01 PM, Yuxuan Shui wrote:
> Hi,
>
> Why is there no opIndexDispatch for overloading a[x].func() ?

I could not understand the question fully but would using an element 
proxy work?

import std.stdio;

struct ElementProxy {
     size_t index;

     void opDispatch(string name, Args...)(Args args) {
         writefln("%s() is called for index %s with args %s", name, 
index, [ args ]);
     }
}

struct A {
     auto opIndex(size_t index) {
         return ElementProxy(index);
     }
}

void main() {
     auto a = A();
     a[0].foo(42);
     a[1].bar("hello", "world");
}

Prints

foo() is called for index 0 with args [42]
bar() is called for index 1 with args ["hello", "world"]

Ali



More information about the Digitalmars-d-learn mailing list