structs, templates, alias

Ellery Newcomer ellery-newcomer at utulsa.edu
Sun Apr 25 13:21:32 PDT 2010


On 04/25/2010 02:50 PM, Robert Clipsham wrote:
> On 25/04/10 20:32, Ellery Newcomer wrote:
>> Hmm. Either I'm not understanding you or I didn't explain something
>> clearly.
>>
>> something like this
>>
>> struct Rec2{
>> ushort index;
>> ushort nparams;
>> ushort options;
>> ushort[] params; // this has nparams elements
>> }
>>
>> Rec2 rec2 = {index:1, nparams:2, options:~0, params:[4,5]};
>>
>> would translate to something like
>>
>> x"01 00 02 00 FF FF 04 00 05 00"
>>
>> only the elements part of params gets written out, the length part
>> doesn't.
>
> Ah, I didn't know this. In which case you should be able to store
> nparams for use later when the array is encountered, then parse as
> appropriate?

Yeah. The trick is generalizing it. I have about a bazillion different 
record types, and I want my read/write routines to operate only on the 
type information provided by tupleof as much as possible, so the 
structure of each struct documents what it looks like in a binary form. 
Something like the following could work

struct Rec2{
   ushort index;
   ushort nparams;
   ushort options;
   NoLength!(Parameter[], "nparams") params;
}
...
foreach(i,m; rec2.tupleof){
   static if(isNoLength!(typeof(m))){
     auto len = lenField!(rec2, typeof(m));
     ...
   }else{
     ...
   }
}

The other thing is, once I've read something in, I'm probably going to 
want to manipulate it. As above, to maintain consistency, whenever I do

rec2.params ~= p;

I'd have to make sure to do

rec2.nparams ++;

I'd like to have the second statement come for free (although I suppose 
I should just ignore nparams for anything but reading in and use 
params.length instead), but I haven't come up with any way to get 
NoLength to see nparams.

I bet this would be easier in D2.


More information about the Digitalmars-d-learn mailing list