Search⌘ K

UDA Example

Explore how to use User Defined Attributes in D programming to flexibly manage struct members. Understand the process of detecting attributes such as encrypted or colored, converting member values to strings, and printing them in XML format using function templates. This lesson helps you grasp attribute-based customization and compile-time evaluations in D.

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:

D
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:

...