std.v2 builder pattern replacement

monkyyy crazymonkyyy at gmail.com
Fri Jul 22 19:06:05 UTC 2022


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 withRefMe(string mixin_,Me,T...)(ref Me me,T arg){
	with(me){
		mixin(mixin_);
	}
	import std.algorithm;
	static if(!mixin_.canFind("return")){
		return me;
	}
}

struct complextype{
	bool isfoo,isbar,isfoobar;
	int i;
	float f;
	bool b;
}
struct point{
	int x,y,xv,yv;
}
alias atZero=withMe!(q{return x==0 && y==0;},point);
void main(){
	import std.stdio;
	auto p=point(1,2,3,4);
	p.withRefMe!q{x=xv;y=yv;};//update a simple object
	p.writeln;
	p.atZero.writeln;
	p.withRefMe!q{x=0;y=0;};
	p.atZero.writeln;
	auto foo=complextype().withMe!q{
		isfoo=true;
		i=1337;
	}();
	auto bar=complextype().withMe!q{
		isbar=true;
		f=4.20;
	};
	auto foobar=complextype().withMe!q{
		isfoobar=true;
		b=true;
	};
	writeln(foo);
	writeln(bar);
	writeln(foobar);
}
```

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


More information about the Digitalmars-d mailing list