On 9 March 2012 18:15, Andrei Alexandrescu <SeeWebsiteForEmail@erdani.org> wrote:
On 3/9/12 2:56 AM, Manu wrote:
Does D have a nice way to add annotations or custom attributes to entities?

In Java/C# for example, it is common to annotate things with useful
compile time information. I'd like to be able to do that in D on occasion.

For instance, I'm serialising some struct/class using reflection to some
text format, but there are a couple of members in a particular class
that I don't want to be written.
A nice solution might be that I could annotate various members:
@DoNotSerialise int thing; ... or something along those lines, whatever
concept you want to apply, which I could then inspect in static if()
logic to produce some requested additional behaviour.

This is a trivial example, but looking at C#/Java, you can see how many
useful things can be done with this sort of system.
How would it be done currently?

I think a good approach in D would be to define mixins that work in conjunction with the feature involved, for example:

class A {
   int thing;
   mixin(DoNotSerialize!"thing");
   ...
}

or together:

class A {
   mixin(DoNotSerialize!(int, "thing"));
   ...
}


Andrei

Yep, that sure is horribly ugly! Sadly, that's what I thought the case was currently. Let's hope for user defined attributes in the future ;)