Difference between revisions of "Mixin Macros Pattern"
(Added solution) |
(→Solution: Mixins + Compile-Time Magic) |
||
Line 10: | Line 10: | ||
== Solution: Mixins + Compile-Time Magic == | == Solution: Mixins + Compile-Time Magic == | ||
<syntaxhighlight lang="d"> | <syntaxhighlight lang="d"> | ||
− | // D operator overloading was designed around mixins | + | // D's operator overloading was designed around mixins |
struct Int | struct Int | ||
{ | { |
Revision as of 13:40, 14 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'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);
}