iterating through members of bitfields

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 17 17:15:05 PST 2017


On 01/17/2017 04:37 PM, Nestor wrote:
> Hi,
>
> I was just looking at an interesting function from
> http://codepad.org/lSDTFd7E :
>
> void printFields(T)(T args) {
>   auto values = args.tupleof;
>
>   size_t max;
>   size_t temp;
>   foreach (index, value; values) {
>     temp = T.tupleof[index].stringof.length;
>     if (max < temp) max = temp;
>   }
>   max += 1;
>   foreach (index, value; values) {
>     writefln("%-" ~ to!string(max) ~ "s %s", T.tupleof[index].stringof,
> value);
>   }
> }
>
> Can something similar be done for bitfields? I tried running this and I
> only get something like this:
>
> _f01_f02_f03      25312
> _f04_f05_f06_f07  21129
> _f08_f09_f10      53575
> _f11_f12_f13_f14  9264
>

Not available but it should be possible to parse the produced code:

import std.bitmanip;

string makeBitFieldPrinter(string fieldImpl) {
     return q{
         void printBitFields() const {
             import std.stdio: writeln;
             writeln("Please improve this function by parsing fieldImpl. 
:)");
         }
     };
}

struct S {
     enum myFields = bitfields!(int, "a", 24,
                                byte, "b", 8);

     pragma(msg, "This is the mixed-in bit field code\n---------\n",
            myFields, "\n----------");


     mixin (myFields);
     mixin (makeBitFieldPrinter(myFields));
}

void main() {
     const s = S();
     s.printBitFields();
}

Of course that would depend on the implementation of bitfields(), which 
can change without notice.

Ali



More information about the Digitalmars-d-learn mailing list