I believe template mixin are the way to go for structs. Small annotated example:

// http://dpaste.1azy.net/56dd2513

mixin template Operators()
{
// Verify "a" field exists for better compile-time error. Hard-coded here. // As an alternative, name of field to use can be provided as a template argument.
        static assert(is(typeof(typeof(this).init.a)),
"class/struct that used this template mixin must have 'a' member declared");
        
// Simple implementation for opBinary. As template mixins use scope of instatiator, // "this" will have target class/struct type. Basically, you can write here any
        // implementation you would normally do in a base class.
        typeof(this) opBinary(string op)(typeof(this) rhs)
                if (op == "+")
        {
                return Test(this.a + rhs.a);
        }
}

struct Test
{
        int a;
        
        // that simple, almost same code amount as with "Test : TestBase"
        mixin Operators;
}

void main()
{
        Test x1 = { 2 };
        Test x2 = { 3 };
        import std.stdio;
        // prints "Test(5)"
        writeln(x1 + x2);
}

Reply via email to