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

Ki Rill rill.ki at yahoo.com
Tue Jun 6 03:34:36 UTC 2023


On Monday, 5 June 2023 at 18:54:30 UTC, cc wrote:
> 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);
> }
> ```

Thank you! That is exactly what I needed. Although another 
solution provided by Basile B. using attributes opens a door for 
other posibilities...

I don't usually use metaprogramming or code generation much, this 
is an eye-opening experience.


More information about the Digitalmars-d-learn mailing list