Difference between revisions of "Mixin Macros Pattern"

From D Wiki
Jump to: navigation, search
(Solution: Mixins + Compile-Time Magic)
(Solution: Mixins + Compile-Time Magic)
Line 15: Line 15:
 
     Int opBinary(string op)(Int rhs)
 
     Int opBinary(string op)(Int rhs)
 
     {
 
     {
       int value = mixin("value_ " ~ op ~ "rhs.value_");
+
       int value = mixin("value_ " ~ op ~ " rhs.value_");
 
       return Int(value);
 
       return Int(value);
 
     }
 
     }

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