On 2016-12-01 21:31, Ethan Watson wrote:
https://github.com/Remedy-Entertainment/binderoo/blob/master/binderoo_client/d/src/binderoo/bitpacking.d


So I've been not-all-that-pleased with std.bitmanip.bitfields for a
while. It's nice that it's there, but I'm binding to C++ objects where
the meaningful default values require those packed values to have
initial values. It's rather painful to get that working with the Phobos
implementation.

I wanted to make a bitfield where you would simply give it a dummy
struct type, complete with UDAs to tell it how many bits to take as well
as standard default values. For example:

struct SomeBitField
{
  @PackSize( 3 ) int iSomeInt = 3;
  @PackSize( 1 ) bool bSomeBool = true;
  @PackSize( 4 ) int iSomeOtherInt;
}

I also don't want this struct to exist outside of the mixin declaration
for it. Essentially, I want the code to boil down to:

mixin BitPack!( struct {
  @PackSize( 3 ) int iSomeInt = 3;
  @PackSize( 1 ) bool bSomeBool = true;
  @PackSize( 4 ) int iSomeOtherInt;
} );

Nice. Readable. Maintainable. You don't even need to read the
documentation to add new members to the bit field, or change default
values.

The compiler disagrees though. The second it sees that struct keyword,
it freaks out. Sigh. Alrighty, what if we just remove the struct
keyword? Nope. It tells me that I'm actually passing a lambda in to the
BitPack mixin template.

Seems like a job for AST macros :). But wWhat about an anonymous class as ag0aep6g mentioned? This compiles and prints "iSomeInt" as expected:

template Foo(T)
{
    pragma(msg, __traits(identifier, T.tupleof[0]));
}

struct PackSize
{
    int size;
}

void main()
{
    mixin Foo!(
        typeof(
            new class {
                @PackSize( 3 ) int iSomeInt = 3;
                @PackSize( 1 ) bool bSomeBool = true;
                @PackSize( 4 ) int iSomeOtherInt;
            }
        )
    );
}

--
/Jacob Carlborg

Reply via email to