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

Basile B. b2.temp at gmx.com
Mon Jun 5 15:33:13 UTC 2023


On Monday, 5 June 2023 at 15:13:43 UTC, Basile B. wrote:
> On Monday, 5 June 2023 at 13:57:20 UTC, Ki Rill wrote:
>> How do I generate `setX` methods for all private mutable
>
> although I did not spent time on the setter body... I suppose 
> the question was more about the metprogramming technic, and 
> that you don't want a pre-mashed solution ;)

By the way...an other solution is to use 
[opDispatch](https://dlang.org/spec/operatoroverloading.html#dispatch):

```d
class Color {}

class Rectangle {
     private Color fillColor;
     private Color strokeColor;
     private uint strokeWidth;

     auto opDispatch(string member, T)(auto ref T t)
     {
              static if (member == "setStrokeWidth") {}
         else static if (member == "setStrokeColor") {}
         else static if (member == "setFillColor") {}
         else static assert(0, "cannot set " ~ member);
         return this;
     }
}

void main()
{
     (new Rectangle)
         .setStrokeWidth(0)
         .setStrokeColor(null)
         .setFillColor(null);
}
```

Sure the first solution takes advantage of D features but to 
generate code that finally looks like C# or Delphi (`Set`, `Get`; 
`property`, etc.)

On top of that I tend to prefer the later solution because 
self-introspection based on `__traits` has corner issues, 
especially when typecons-like structures are used for the members 
(e.g sumtype, nullable, etc.).


More information about the Digitalmars-d-learn mailing list