www.digitalmars.com

D Programming Language 2.0


Last update Mon Dec 31 02:58:02 2012

Mixins

Mixins (not to be confused with template mixins) enable string constants to be compiled as regular D code and inserted into the program. Combining this with compile time manipulation of strings enables the creation of domain-specific languages.

For example, here we can create a template that generates a struct with the named members:

template GenStruct(string Name, string M1)
{
    const char[] GenStruct = "struct " ~ Name ~ "{ int " ~ M1 ~ "; }";
}

mixin(GenStruct!("Foo", "bar"));

which generates:

struct Foo { int bar; }

Superficially, since D mixins can manipulate text and compile the result, it has some similar properties to the C preprocessor. But there are major, fundamental differences:





Forums | Comments |  D  | Search | Downloads | Home