User Defined Attributes (UDA) in Phobos/druntime

Jacob Carlborg doob at me.com
Wed Jun 12 09:20:58 PDT 2013


On 2013-06-12 14:29, Andrej Mitrovic wrote:

> But without this you lose the ability to customize. I don't like just
> "tagging" something, I like D's ability where you can actually
> customize the UDA, for example:
>
> -----
> import std.typetuple;
>
> struct Server
> {
>      string url;
> }
>
> struct Config
> {
>      @(Server("http://foo.bar")) string name;
>      @(Server("http://doo.bar")) string[] items;
> }
>
> template GetAttributes(T...) if (T.length == 1)
> {
>      alias GetAttributes = TypeTuple!(__traits(getAttributes, T[0]));
> }
>
> void main()
> {
>      Config config;
>
>      alias attribs = GetAttributes!(config.name);
>
>      static if (attribs.length && is(typeof(attribs[0]) == test.Server))
>      {
>          pragma(msg, attribs[0]);
>      }
> }
> -----
>
> Thanks to CTFE we can tag a field with a struct that may have any
> state. All you have to do in the library code is to first check if any
> of the attributes is an "attribute type (a struct of some sort)" that
> you recognize, and then read its state.

As far as I know other language allows UDA's to be of any type/value. 
Java uses the @annotation annotation on an interface and in C# classes 
with System.Attribute as the base class are used.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list