std.v2 builder pattern replacement
Salih Dincer
salihdb at hotmail.com
Sat Jul 23 13:58:46 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 withMe(string mixin_,Me,T...)(Me me,T arg){
> with(me){
> mixin(mixin_);
> }
> import std.algorithm;
> static if(!mixin_.canFind("return")){
> return me;
> }
> }
> auto foo=complextype().withMe!q{
> isfoo=true;
> i=1337;
> }();
> ```
This convenience function looks very useful. However, when I try,
initA and initB give the same result. Moreover, the classic
C-style is much shorter and similar:
```d
import std.stdio;
struct Harf {
char harf = 96;
string toString() { return [harf]; }
}
enum { A = 97, B, C, D }
enum a = Harf(A);
enum b = Harf(B);
auto withMe(string elements, Me, T...)(Me me, T arg){
with(me) mixin(elements);
return me;
}
void main() {
struct S {
Harf[] hler;
int[] nler;
int n;
}
/* toggleCode:
auto initA = S().withMe!q{
hler = [a, b];
nler = [1, 2];
n = 3;
};
initA.writeln;
/*/
S initB = {
hler : [a, b],
nler : [1, 2],
n : 3
};
initB.writeln;
//*/
} /* Prints:
S([a, b], [1, 2], 3)
*/
```
Respects...
SDB at 79
More information about the Digitalmars-d
mailing list