Overloading operators by operator symbol
Jarrett Billingsley
kb3ctd2 at yahoo.com
Sat Oct 28 05:53:44 PDT 2006
"Bill Baxter" <wbaxter at gmail.com> wrote in message
news:ehv8kj$1d4$1 at digitaldaemon.com...
> 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;
> }
Basically you've just replaced "opAdd" etc. with "myPlus" etc. ;) I know
what you're getting at but..
> 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?
I think we'd have to have the ability to dynamically generate symbols with
templates (i.e. some form of token pasting) in order for this to be
possible. But then, of course, you have the problem of not being able to
declare delegates at a class level, which would make it hard to pass the
implementation into the Operator template..
More information about the Digitalmars-d
mailing list