root/trunk/docsrc/mixin.dd

Revision 659, 2.1 kB (checked in by andrei, 4 years ago)

Changed ddoc extensions to dd and changed linux.mak accordingly

  • Property svn:eol-style set to native
Line 
1 Ddoc
2
3 $(D_S Mixins,
4
5     $(P Mixins (not to be confused with
6     $(LINK2 template-mixin.html, template mixins))
7     enable string constants to be compiled as regular D code
8     and inserted into the program.
9     Combining this with compile time manipulation of strings
10     enables the creation of domain-specific languages.
11     )
12
13     $(P For example, here we can create a template that generates
14     a struct with the named members:
15     )
16
17 ---
18 template GenStruct(char[] Name, char[] M1)
19 {
20     const char[] GenStruct = "struct " ~ Name ~ "{ int " ~ M1 ~ "; }";
21 }
22
23 mixin(GenStruct!("Foo", "bar"));
24 ---
25     $(P which generates:)
26 ---
27 struct Foo { int bar; }
28 ---
29
30
31     $(P Superficially, since D mixins can manipulate text and compile
32     the result, it has some similar properties to the C preprocessor.
33     But there are major, fundamental differences:
34     )
35
36 $(UL
37
38     $(LI The C preprocessing step occurs $(B before) lexical analysis.
39     This makes it impossible to lex or parse C without access to
40     all of the context, including all #include'd files, paths and all
41     relevant compiler switches.
42
43     Mixins occur during semantic analysis, and do not affect
44     the lexing or parsing process.
45     Lexing and parsing can still occur without semantic analysis.
46     )
47
48
49     $(LI The C preprocessor can be used to create what appears to
50     be different syntax:
51
52 $(CCODE
53 #define BEGIN {
54 #define END   }
55
56 BEGIN
57   int x = 3;
58   foo(x);
59 END
60 )
61
62     This monkey business is impossible with mixins.
63     Mixed in text must form complete declarations,
64     statements, or expressions.
65     )
66
67     $(LI C macros will affect everything following that has
68     the same name, even if they are in nested scopes.
69     C macros cut across all scopes.
70     This problem is called being not "coding hygenic".
71
72     Mixins follow the usual scoping rules, and is
73     hygenic.
74     )
75
76     $(LI C preprocessing expressions follow a different syntax
77     and have different semantic rules than the C language.
78     The C preprocessor is technically a different language.
79
80     Mixins are in the same language.
81     )
82
83     $(LI C const declarations and C++ templates are invisible
84     to C preprocessing.
85
86     Mixins can be manipulated using templates and const
87     declarations.
88     )
89 )
90
91 )
92
93 Macros:
94     TITLE=Mixins
95     WIKI=Mixins
Note: See TracBrowser for help on using the browser.