Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. Create a struct or enum to use as the attribute. A struct attribute should have data members, as shown in the following code. An enum attribute is best used for a simple flag:

    struct MyNote { string note; }
  2. Attach the attribute to a declaration with the @ sigil, as shown in the following code:

    @MyNote("this is my note on foo") void foo() {}
  3. Retrieve attributes by using the __traits(getAttributes, symbol) function. To pass the symbol to a function or template, use a compile-time parameter with the alias keyword.

  4. 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...