User Defined Attributes (UDA) in Phobos/druntime

Andrej Mitrovic andrej.mitrovich at gmail.com
Wed Jun 12 05:29:40 PDT 2013


On 6/11/13, Jacob Carlborg <doob at me.com> wrote:
> I was kind of disappointed with the way D implemented UDA's. Just dump
> any value/type to a symbol.

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.


More information about the Digitalmars-d mailing list