On 01/16/2013 09:45 PM, Era Scarecrow wrote:

> (Do they have to be structs?) If they
> don't and you add code, can that code help/add or modify the attributed
> object (or can it at all?).

It looks like some mixin magic can be used.

> Do the structs have to be empty?

They can have members. getAttributes preserves the types and values of the attributes. It returns a tuple.

With the warning that I don't have any experience with attributes, the following program uses an attribute type that has a member to indicate the number of times that a variable must be serialized. (Stupid idea. :))

import std.stdio;

struct Serialize
{
    size_t count;
}

struct S
{
    @Serialize(3) int x;
    int y;
    @Serialize(2) int z;
}

void foo(T)(T s)
{
    foreach (member; __traits(allMembers, T)) {
        foreach (attr;
__traits(getAttributes, mixin(T.stringof ~ '.' ~ member))) {
            if (typeid(attr) is typeid(Serialize)) {
                writefln("%s has %s", member, attr);
                writefln("must serialize %s %s times", member, attr.count);

                foreach (count; 0 .. attr.count) {
                    writefln("  serializing %s", member);
                }
            }
        }
    }
}

void main()
{
    auto s = S();
    foo(s);
}

The output shows that only x and z are serialized according to their respective serialization counts:

x has Serialize(3)
must serialize x 3 times
  serializing x
  serializing x
  serializing x
z has Serialize(2)
must serialize z 2 times
  serializing z
  serializing z

Ali

Reply via email to