Reordered class fields?

Peter Summerland p.summerland at gmail.com
Wed Oct 31 01:14:42 PDT 2012


On Wednesday, 31 October 2012 at 07:19:19 UTC, Jacob Carlborg 
wrote:
> On 2012-10-31 02:53, Peter Summerland wrote:
>
>> The order of the fields is rearranged for packing. Does that 
>> affect the
>> tupleof property? The example in http://dlang.org/class.html 
>> for Class
>> properties tulpleof seems to implie that the the fields the 
>> returned
>> Expression Tuple are arranged in lexical order (i.e., as 
>> defined by the
>> programmer in the class definition). Is this always true for 
>> classes?
>> What about structs?
>
> I don't know. But I would not count on the order of tupleof. I 
> would consider that implementation defined.

Thanks for the help.

Should the the following example, taken from the D Language 
Reference, be considered incorrect or at least misleading? It 
clearly depends on lexical ordering of the returned fields:

Class Properties

The .tupleof property returns an ExpressionTuple of all the 
fields in the class, excluding the hidden fields and the fields 
in the base class.

class Foo { int x; long y; }
void test(Foo foo) {
   foo.tupleof[0] = 1; // set foo.x to 1
   foo.tupleof[1] = 2; // set foo.y to 2
   foreach (x; foo.tupleof)
     writef(x);        // prints 12
}


It would be nice if the Language Reference was specific on this 
point.  I am aware that the order of the members returned by 
__traits(allMembers, D) is not defined (per the LR). But that is 
a larger, more complex list.

I am just beginning with D, but I think having the tupleof 
property for classes and structs return their fields in lexical 
order might be useful.

E.g., I have written a "scan" function to load up a struct or 
class from a row returned by a database query. I have, say, 
scan!"x,y,z"(obj) to load data into fields x,y,z of obj. Based on 
the example above and by experimenting, it appears that at least 
for dmd running on Linux, that the fields returned by tupleof are 
indeed in lexical order.  That allowed me to have a "" default 
for the string of field names which indicates that all the fields 
should be loaded. I.e., I have scan!""(obj), which can be written 
scan(obj). Again, it seems to work for simple classes and structs 
with Dmd on Ubuntu.

Don't get me wrong -- I'll be happy without the default version 
if that is the answer. I'm not suggesting any changes.





More information about the Digitalmars-d-learn mailing list