opIndexOpAssignOpDispatch
Quirin Schroll
qs.il.paperinik at gmail.com
Mon Jun 17 13:40:13 UTC 2024
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;
}
```
More information about the dip.ideas
mailing list