Difference between revisions of "Mixin Macros Pattern"
(Start of content creation) |
(Added solution) |
||
Line 7: | Line 7: | ||
* Ability to use templates/CTFE | * Ability to use templates/CTFE | ||
* <code>(Avoid (Lispy (syntax)))</code> | * <code>(Avoid (Lispy (syntax)))</code> | ||
+ | |||
+ | == Solution: Mixins + Compile-Time Magic == | ||
+ | <syntaxhighlight lang="d"> | ||
+ | // D operator overloading was designed around mixins | ||
+ | struct Int | ||
+ | { | ||
+ | Int opBinary(string op)(Int rhs) | ||
+ | { | ||
+ | int value = mixin("value_ " ~ op ~ "rhs.value_"); | ||
+ | return Int(value); | ||
+ | } | ||
+ | |||
+ | int value() @property | ||
+ | { | ||
+ | return value_; | ||
+ | } | ||
+ | |||
+ | private int value_; | ||
+ | } | ||
+ | |||
+ | void main() | ||
+ | { | ||
+ | assert((Int(2) - Int(5)).value == -3); | ||
+ | assert((Int(2) + Int(4)).value == 7); | ||
+ | } | ||
+ | </syntaxhighlight> |
Revision as of 11:21, 10 August 2014
From David Simcha's D-Specific Design Patterns talk at DConf 2013.
Problem: Repetitive code with slight variations
Example: Arithmetic operator overloading Want:
- Minimal code duplication
- Ability to use templates/CTFE
(Avoid (Lispy (syntax)))
Solution: Mixins + Compile-Time Magic
// D operator overloading was designed around mixins
struct Int
{
Int opBinary(string op)(Int rhs)
{
int value = mixin("value_ " ~ op ~ "rhs.value_");
return Int(value);
}
int value() @property
{
return value_;
}
private int value_;
}
void main()
{
assert((Int(2) - Int(5)).value == -3);
assert((Int(2) + Int(4)).value == 7);
}