Define an order for allMembers traits
Andrey Zherikov
andrey.zherikov at gmail.com
Wed Aug 23 12:32:58 UTC 2023
D doc for for `__traits(allMembers, ...)`
[says](https://dlang.org/spec/traits.html#allMembers) that "the
order in which the strings appear in the result is not defined".
Is it possible to define an order at least for some cases (I'm
looking for structs actually)?
I think having guaranteed order for simple cases in beneficial:
```d
struct S
{
int a,b;
string c,d;
}
assert([ __traits(allMembers, S) ] == [ "a","b","c","d" ]);
```
This will especially help in my use case where I need to know the
order in which struct members are declared. Right now I'm using
UDA with index to explicitly set an order:
```d
struct S
{
@UDA(1) int a;
@UDA(2) int b;
@UDA(3) string c;
@UDA(4) string d;
}
```
Possible solution would be to use `__LINE__` but it won't work in
this case:
```d
struct S
{
@UDA int a; @UDA int b;
}
```
The only solution that might work is to use
`__traits(getLocation, ...)` which complicates introspection a
lot: instead of simple usage of `__traits(allMembers, ...)` I'll
have to sort all members by location and only then iterate over
them.
More information about the Digitalmars-d
mailing list