mardi 20 décembre 2016

D language: Iterate over members of a struct and check a UDA (runtime reflection)

In D language, I want to iterate over a structure and perform logic specific to each annotation attached to each member. Ex.

struct Pattern {
    string pattern;
}

string Max {
    int max;
}

string Min {
    int min;
}

struct StructToValidate {
    @Pattern("^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$")
    string phone;

    @Max(20)
    @Min(3)
    int someValue;
}

and then in a function, do something like this:

int main() {
    StructToValidate struct;

    // begin pseudocode
    // for each member of struct mem = [phone, someValue] {
    //     if (hasUDA!(mem, Pattern)) {
    //         do stuff like validation on the runtime value of this member
    //     } else if (hasUDA!(mem, Min)) {
    //         ...
    //     } else if (hasUDA!(mem, Max)) {
    //         ...
    //     }
    // }
    //
    return 0;
}

How do I do this?





Aucun commentaire:

Enregistrer un commentaire