UDA Example

Let’s understand UDA with the help of an example.

We'll cover the following...

Example

Let’s design a function template that prints the values of all members of a struct object in XML format. The following function considers the Encrypted and Colored attributes of each member when producing the output:

Press + to interact
void printAsXML(T)(T object) {
//...
foreach (member; __traits(allMembers, T)) { // 1
string value =
__traits(getMember, object, member).to!string; // 2
static if (hasUDA!(__traits(getMember, T, member), // 3
Encrypted)) {
value = value.encrypted.to!string;
}
writefln(` <%1$s color="%2$s">%3$s</%1$s>`,
member, colorAttributeOf!(T, member), value); // 4
}
}

The numbered parts of the code are explained below:

...