Mixin Macros Pattern

From D Wiki
Revision as of 13:40, 14 August 2014 by Verax (talk | contribs) (Solution: Mixins + Compile-Time Magic)
Jump to: navigation, search

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);
}