Chuyển đến nội dung

Bài 26 · Mixins and Metaprogramming

Traits, static if and Compile-Time Reflection in D

Learn D compile-time reflection: __traits, static if, static foreach, version blocks and std.traits for inspecting types and members, with C _Generic and offsetof stand-ins.

Templates, CTFE and mixins become really powerful when your code can look at types and decide what to generate. D provides this with static if, static foreach, version and the __traits keyword. Together they form D's compile-time reflection: questions are answered while compiling, so the result costs nothing at run time.

D code is read-only on this site. The C stand-ins use sizeof, offsetof, _Generic and #if, which answer a few of the same questions in a much smaller way.

static if

static if is an if evaluated by the compiler. The branch not taken is not even type-checked, which is what makes it useful in generic code:

D
void show(T)(T value)
{
    static if (is(T == string))
        writeln("text: ", value);
    else static if (__traits(isArithmetic, T))
        writeln("number: ", value);
    else
        writeln("other: ", value.stringof);
}

Unlike a normal if, static if does not open a new scope for declarations, so it can conditionally declare members of a struct or module:

D
struct Pixel(bool hasAlpha)
{
    ubyte r, g, b;
    static if (hasAlpha) ubyte a;
}

Pixel!false has three fields and Pixel!true has four.

version blocks

version selects code per platform or build flag, similar to the C preprocessor but structured:

D
version (Windows) enum separator = '\\';
else version (Posix) enum separator = '/';
else static assert(0, "unsupported platform");

version (unittest) { /* only in test builds */ }

Predefined identifiers include Windows, linux, OSX, X86_64, LittleEndian, D_BetterC and unittest. Your own come from -version=Name on the command line. debug blocks are a sibling feature, compiled only with -debug.

C Stand-in: conditional compilation with #if

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

__traits

__traits(name, arguments) is a family of compile-time queries. A few of the most useful:

Trait Answers
allMembers the names of all members of a type or module
getMember a member by name (for generic access)
hasMember does the type have a member with this name?
isArithmetic, isIntegral, isStaticArray category tests
compiles does this expression compile?
getAttributes user attributes attached to a symbol
identifier a symbol's name as a string
isSame are two symbols the same thing?
D
struct Sensor { int id; double reading; string label; }

static foreach (name; __traits(allMembers, Sensor))
{
    pragma(msg, name);       // id, reading, label (at compile time)
}

__traits(compiles, expr) is the duck-typing test: it is true when expr compiles in the current context, and it never produces an error itself. That is how you check "does x.length work?" or "can I add these two values?" without naming a type.

static foreach and generating code

static foreach unrolls a loop at compile time, and each iteration may declare symbols:

D
static foreach (i; 0 .. 3)
{
    mixin("int slot", i, " = ", i * 10, ";");   // slot0, slot1, slot2
}

Combined with allMembers, you can generate a generic printer for any struct:

D
void dump(T)(T value)
{
    foreach (name; __traits(allMembers, T))
    {
        static if (!is(typeof(__traits(getMember, T, name)) == function))
            writeln(name, " = ", __traits(getMember, value, name));
    }
}

dump(Sensor(1, 20.5, "cpu")) prints each field name and value, and works for any struct you will ever define: one function, no hand-written boilerplate. The same pattern powers serializers, command-line parsers, and database mappers.

User-defined attributes

You can tag declarations with attributes and read them back through traits:

D
struct Column { string name; }

struct User
{
    @Column("user_id") int id;
    @Column("email")   string email;
}

__traits(getAttributes, User.id) returns the Column("user_id") value as a compile-time tuple, so an ORM can derive column names without any registration code.

std.traits

Most programs use the library layer over __traits: Fields!T (field types), FieldNameTuple!T, ReturnType!F, Parameters!F, isCallable!F, hasUDA!(sym, Attr). Reach for these first; they are named for what they mean and are documented.

Stand-ins: layout reflection and type names

C has no reflection, but offsetof, sizeof and _Generic reveal a little. The program below prints a struct's layout, the information a D allMembers-based dumper would compute for you.

C Stand-in: inspecting a struct layout

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Stand-in: a type name as a compile-time string

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

flowchart LR
    A["Your type T"] --> B["__traits / std.traits"]
    B --> C["static if / static foreach"]
    C --> D["Generated members, serializers, checks"]

Reflection results feed code generation, all before the program runs.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What makes static if different from if?

    static if selects code during compilation, and its declarations do not open a new scope.
  2. 2. What is __traits(compiles, expr) useful for?

    It returns a boolean, enabling duck-typed constraints.
  3. 3. Which trait lists the names of all members of a type?

    __traits(allMembers, T) yields the member names as a compile-time tuple.
  4. 4. How do you select Windows-specific code?

    D uses version blocks with predefined identifiers.

Summary

  • static if, static foreach and version choose and generate code at compile time.
  • __traits and std.traits inspect types, members and attributes.
  • With mixins and CTFE they power serializers, ORMs and zero-cost generic utilities.

Next: Parallelism with std.parallelism

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.