On Thursday, 19 July 2018 at 19:18:43 UTC, jmh530 wrote:
I wanted to create a struct with a member function whose behavior was different depending on whether the struct instance had a particular UDA.

However, it seems like hasUDA doesn't seem to produce the result I would have expected here. I tried using getAttributes, but that didn't work either.

Am I missing something, or should I submit an enhancement request?



import std.traits : hasUDA;

enum test;

struct Foo
{
    int x;

    bool checkUDA()
    {
        static if (hasUDA!(this, test))
        {
                return true;
        }
        else
        {
                return false;
        }
    }
}


void main()
{
    import std.stdio : writeln;

    @test Foo foo = Foo(1);
    static assert(hasUDA!(foo, test));

    writeln(foo.checkUDA()); //prints false, expected true
}

I haven't worked with UDAs myself yet, but I believe that when you apply something like

@test Foo foo;

then you apply the UDA to `foo` and not to `Foo`.

See below:

enum test;

struct Foo
{}

bool checkUDA(alias f)()
{
    static if (hasUDA!(f, test))
    {
        return true;
    }
    else
    {
        return false;
    }
}

void main()
{
    @test Foo foo;
    // same as `hasUDA!(foo, test)`
    assert(checkUDA!foo); //prints true
}

Now I'm really not sure how UDAs are best utilized, so above example might not be how it should be done.. However, you could make a templated version of checkUDA depending on what calls it. E.g.

bool checkUDA(T, alias f)(T t)
{
    // ...
}

although this leads to awkward calls like

foo.checkUDA!foo

which doesn't seem right either. Perhaps wait for somebody more knowledgeable to answer your question : D.

Reply via email to