"macro" expansion to build switch case code
Steven Schveighoffer
schveiguy at gmail.com
Sun Jul 2 20:27:47 UTC 2023
On 7/2/23 1:02 PM, Paul wrote:
> I have a struct similar to the following example. I'd like to build an
> adder method without having to code the whole method. How do I use the D
> language to do this? Template, mixins, CTFE..all of them?
>
> ```d
> struct myS {
> int a, b, c, d, e, f, g, h, i;
> adder(string s, int n) {
> final switch (s) {
> case "aa" :
> a += n; break;
> case "bb" :
> b += n; break;
> ...
> ```
> Thanks for any assistance.
Use a static foreach:
```d
import std.traits; // for FieldNameTuple. there are other ways, but this
is the most straightforward
switchlabel: // this is needed for break inside a static foreach
final switch(s) {
static foreach(mem; FieldNameTuple!myS) {
case mem ~ mem:
__traits(getMember, this, mem) += n;
break switchalbel;
}
}
```
-Steve
More information about the Digitalmars-d-learn
mailing list