Using user-defined attributes
D supports user-defined attributes (sometimes called annotations), which are a way to add custom compile-time information to declarations that can be retrieved later by reflection. Here, we'll look at their capabilities and their limitations.
How to do it…
Let's execute the following steps to use user-defined attributes:
Create a
struct
orenum
to use as the attribute. Astruct
attribute should have data members, as shown in the following code. Anenum
attribute is best used for a simple flag:struct MyNote { string note; }
Attach the attribute to a declaration with the
@
sigil, as shown in the following code:@MyNote("this is my note on foo") void foo() {}
Retrieve attributes by using the
__traits(getAttributes, symbol)
function. To pass the symbol to a function or template, use a compile-time parameter with thealias
keyword.Loop over the attributes, retrieving the one you want by identifying the type with the basic form of the
is
expression. For flags, check for...