X macro in D

Timon Gehr timon.gehr at gmx.ch
Sat Aug 20 14:15:52 UTC 2022


On 8/20/22 15:11, Walter Bright wrote:
> The X macro in C is famous:
> 
> https://www.digitalmars.com/articles/b51.html
> 
> Here's the challenge:
> 
> "X-macros in C [1] are great for doing compile-time code generation from 
> tabular data. Especially for things like pinouts and their respective 
> capabilities on microcontrollers, I haven't seen any other language give 
> such a succinct, easily maintainable way of interacting and representing 
> data such that it can be used for full function generation that an IDE 
> can autocomplete names, types etc.
> Sure there are other "newer" ways but they invariably involve so much 
> boilerplate that you might as well just write all the code by hand."
> 
> https://news.ycombinator.com/item?id=32530255
> 
> Who is up for the challenge?

Not much of a challenge.

Your example:

```d
enum Color { red, blue, green }
static immutable colorStrings = [EnumMembers!Color].map!text.array;
static foreach(color;EnumMembers!Color){ ... }
```

Example 1 from Wikipedia:

```d
auto value1=1,value2=2,value3=3;
alias vars=AliasSeq!(value1,value2,value3);
void printVariables(){
     static foreach(alias var;vars){
         writeln(__traits(identifier, var), " = ", var);
     }
}
```

Example 2 from Wikipedia:

enum id1=1, id2=2, id3=3;

static immutable varList = [
     tuple("id1", "name1"),
     tuple("id2", "name2"),
     tuple("id3", "name3"),
];

static foreach(id, name; varList.map!(x=>x)){ // yuck
     mixin(`int `~name~`;`);
}

mixin(`enum MyIdListType{`~varList.map!(x=>x[1]~"="~x[0]).join(",")~`}`);

Does not allow you to add new columns transparently, but I guess we'd 
need actual tuple pattern matching for that (or do everything via indices).


More information about the Digitalmars-d mailing list