Overloading operators by operator symbol

Bill Baxter wbaxter at gmail.com
Sat Oct 28 02:41:37 PDT 2006


I'm not a big fan of magic operator method names.  Python has its 
__add__ etc methods, Lua has very similar, D has opAdd etc.
Personally I prefer C++'s way of just using the syntax itself.  I find 
it a lot easier to remember and it looks less "magical".

I started wondering if it might be able to accomplish something like 
that using mixins.  Here's an example of what I've gotten to work so far:

class AClass
{
     // Look ma! I'm overloading operators by symbols!
     mixin Operator!("+", myPlus);
     mixin Operator!("+=", myPlusEq);
     mixin Operator!("-", myMinus);
     mixin Operator!("-=", myMinusEq);

     // the actual operator overload implementations
     int myPlus(int v){ return m_value + v; };
     int myMinus(int v){ return m_value - v; };
     int myPlusEq(int v){ return m_value += v; };
     int myMinusEq(int v){ return m_value -= v; };

     int m_value = 0;
}

void main()
{
     // example use
     AClass a = new AClass();
     a += 3;
     writefln("a is: ", a.m_value);
     writefln("a+5 is: ", a + 5);
     a -= 10;
     writefln("a-=10; a is now: ", a.m_value);
     writefln("a-5 is: ", a - 5);
}

// The guy who makes it happen
template Operator(char[] op, alias OpFn )
{
     // todo: actually derive these types from OpFn
     alias int RetType;
     alias int ArgType;
     static if(op=="+") {
         RetType opAdd(ArgType v) {
             return OpFn(v);
         }
     }
     else static if(op=="-") {
         RetType opSub(ArgType v) {
             return OpFn(v);
         }
     }
     else static if(op=="+=") {
         RetType opAddAssign(ArgType v) {
             return OpFn(v);
         }
     }
     else static if(op=="-=") {
         RetType opSubAssign(ArgType v) {
             return OpFn(v);
         }
     }
}

This is pretty simplistic and not very complete.  Ideally the syntax 
would look more like

     mixin Operator!("-",
        int(int v){ return my_value + v; }
     );

or best

     int Operator!("-")(int v){ return my_value + v; }

But I couldn't figure out any way to make those work. :-)
Can anyone do better?

--bb



More information about the Digitalmars-d mailing list