std.v2 builder pattern replacement

FeepingCreature feepingcreature at gmail.com
Wed Jul 27 09:15:28 UTC 2022


On Friday, 22 July 2022 at 19:06:05 UTC, monkyyy wrote:
> So today I was looking into builder patterns with opDispatch, 
> complained about d's edge cases; throw out some ideas that snar 
> told me instantly wouldn't work etc. etc.
>
> Anyway, the conclusion of this discussion is an idea for a 
> pattern.
>
> ```d
>       ...
> 	auto foo=complextype().withMe!q{
> 		isfoo=true;
> 		i=1337;
> 	}();
>       ...
> ```
>
> At this moment I don't know how to have this compile ref and 
> non ref at the same time.
>
> But I suggest something like this gets into std.v2 and everyone 
> uses it rather than rolling a custom builder in the future

This only works with constants; it cannot function when assigning 
variables from the callsite. You'd need something horrible like

```d
int callerI = 1337;
auto foo = mixin(complextype().withMe!q{ i = callerI; });
```

This is what we use on our end:

```d
import boilerplate;

struct Test { bool isfoo; int i; mixin(GenerateThis); }

...

void main() {
     int callerI = 1337;

     Test foo() {
         with (Test.Builder()) {
             isfoo = true;
             i = callerI;
             return value;
         }
     }
}
```
It's not exactly compact, but it's the best I think can be done 
before named arguments.


More information about the Digitalmars-d mailing list