Difference between revisions of "Mixin Macros Pattern"
(→Solution: Mixins + Compile-Time Magic) |
m (→Problem: Repetitive code with slight variations) |
||
Line 3: | Line 3: | ||
== Problem: Repetitive code with slight variations == | == Problem: Repetitive code with slight variations == | ||
Example: Arithmetic operator overloading | Example: Arithmetic operator overloading | ||
+ | |||
Want: | Want: | ||
* Minimal code duplication | * Minimal code duplication |
Revision as of 11:06, 1 November 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's 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);
}