opIndexOpAssignOpDispatch

Basile B. b2.temp at gmx.com
Tue Jun 18 09:37:46 UTC 2024


On Monday, 17 June 2024 at 13:40:13 UTC, Quirin Schroll wrote:
> On Saturday, 15 June 2024 at 08:33:07 UTC, Basile B. wrote:
>> On Saturday, 15 June 2024 at 04:58:58 UTC, monkyyy wrote:
>>> ```d
>>> mystruct foo;
>>> foo[1337].isnull=true;
>>> ```
>>> =>
>>> `foo.opIndexOpAssignOpDispatch!"isnull"(1337,true)`
>>>
>>> it fits the naming scheme!
>>
>> You can implement an opIndex overload that returns a struct 
>> that itself supports opDispatch.
>>
>> ```d
>> struct Foo
>> {
>>     struct opIndexResult
>>     {
>>         Foo* that;
>>         auto opDispatch(string member, T)(T t)
>>         {
>>
>>         }
>>     }
>>
>>     auto opIndex(T)(T t)
>>     {
>>         return opIndexResult(&this);
>>     }
>> }
>>
>> void main()
>> {
>>     Foo foo;
>>     foo[1337].isnull = true;
>> }
>> ```
>>
>> dont underestimate what's already possible !
>
> ```d
> struct Foo
> {
>     struct opIndexResult(bool isRef, Arg)
>     {
>         Foo* that;
>         static if (isRef)
>         {
>             Arg* _arg;
>             ref Arg arg() => *_arg;
>         }
>         else
>         {
>             Arg _arg;
>             ref Arg arg() return => _arg;
>         }
>         auto ref opDispatch(string member, Rhs)(Rhs rhs)
>         {
> 			import std.stdio;
>             writeln("Called <something>[", arg, "].", member, " 
> = ", rhs);
>         }
>     }
>
>     auto ref opIndex(T)(auto ref T t)
>     {
>         alias Result = opIndexResult!(__traits(isRef, t), T);
>         static if (__traits(isRef, t))
>         {
>             return Result(&this, &t);
>         }
>         else
>         {
>             import core.lifetime : move;
>             return Result(&this, move(t));
>         }
>     }
> }
>
> void main() @safe
> {
>     Foo foo;
>     foo[1337].isnull = true;
> }
> ```

Nice. While the pattern was clear enough to be developped I'm 
still slightly concerned about escaping `this`. Probably the 
result should be set non-copiable with `@disable this(this)`.


More information about the dip.ideas mailing list