Search code examples
d

How to select all member which has a given attribute name with UDA?


Considering an attribute which take a delegate ( predicate function as std.algorithm.filter )

struct Section( alias pred ){}

This is used to annotate a field like this:

struct A {
    @Section!( ( words ) =>  words[0] == '@' )
    string b;
    int c;
}

Field b is annotate by a delegate which return true if a string start by @ when called

So how to retrieve all field which are annotated by @Section ?

Is it possible to called at runtime his delegate with a string as parameter and know if is true or not ?

thanks


Solution

  • So how to retrieve all field which are annotated by @Section ?

    First, use allMembers or .tupleof to enumerate over all the fields of the struct.

    Then, enumerate over all attributes attached to each field using getAttributes. Check if @Section is present in the field.

    Is it possible to called at runtime his delegate with a string as parameter and know if is true or not ?

    You should save an alias within the Section structure. For example:

    struct Section(alias pred)
    {
        alias fun = pred;
    }
    

    Then, just reference the getAttributes result tuple member.