How do I generate `setX` methods for all private mutable variables in a class?

cc cc at nevernet.com
Mon Jun 5 18:54:30 UTC 2023


On Monday, 5 June 2023 at 13:57:20 UTC, Ki Rill wrote:
> How do I generate `setX` methods for all private mutable 
> variables in my class? Do I need to use `__traits`?

```d
mixin template GenerateSetters() {
	static foreach (idx, field; typeof(this).tupleof) static if 
(__traits(getVisibility,field) == "private") {
		mixin(q{
				void %SETTER(typeof(this.tupleof[idx]) _) {
					%NAME = _;
				}
			}
			.replace("%NAME", field.stringof)
			.replace("%SETTER", "set"~toUpper(field.stringof[0..1]) ~ 
field.stringof[1..$])
		);
	}
}
class Rectangle {
	private Color fillColor;
	private Color strokeColor;
	private uint strokeWidth;

	this(int x, int y) {}

	mixin GenerateSetters;
}

void main() {
	auto rect = new Rectangle(0, 0);
	rect.setStrokeWidth(4);
	assert(rect.strokeWidth == 4);
}
```


More information about the Digitalmars-d-learn mailing list