How to list aggregate members in order of declaration at compile time?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Nov 11 14:04:37 PST 2016


On Friday, November 11, 2016 21:26:10 Ivan Kazmenko via Digitalmars-d-learn 
wrote:
> On Thursday, 10 November 2016 at 10:16:44 UTC, Ivan Kazmenko
>
> wrote:
> > I want to somehow list members of a class in the order of their
> > declaration.
>
> Bump.  Anyone?  I've met my immediate goal by other means, but
> the general question remains.
>
> If classes are no-go, basically, any aggregate will do if the
> order of declarations is reliably and reproducibly known at
> compile time.
>
> I'm not much into compile-time reflection, yet, but I thought
> that's a basic operation.  Otherwise, how do people, for example,
> approach serializing arbitrary containers reproducibly across
> compiler versions - or they just don't?  Well, I've seen one
> example (Cerealed), but the implementation details there seem to
> contradict the current language documentation.

I think that the simple truth of the matter is that nothing in the spec
guarantees an order for any of the operations that give a list of members of
a struct or class. It's just that the implementation doesn't typically
change in a way that would change the order, and folks rely on the current
implementation, and it works.

The correct way to get the list of member variables of a struct or class is
the tupleof property. And the only order that really makes sense for it is
the order of declaration. Because of what it is and what it would be used
for with a struct, I think that it would be hard to argue that it would make
any sense for it do anything else. For classes, it's more debatable given
that the member variables rearranged within the object, but since tupleof
only gives you the direct member variables and therefore doesn't give you
the actual layout of the full class anyway, there really isn't any point in
it giving anything but the declaration order. So, it wouldn't surprise me if
Walter would agree to making it so that the spec guarantees that tupleof
gives the member variables in the order that they were declared, but I would
not expect such a guarantee from something like __traits(allMembers, T)
which gives stuff like base class members as well as stuff like functions,
where the order of declaration doesn't matter at all, and there is no
obvious order that members should be listed in when you take stuff like base
classes and interfaces into account.

I expect that it never occurred to Walter to specify that the order of the
members mattered with tupleof and that that's why the spec doesn't say.

So, use tupleof, and you can create an enhancement request in bugzilla for
the spec to be made clearer about it: https://issues.dlang.org

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list