Operator Overloading - elegant and easy to compile

Tomasz Sowinski tomeksowi at gmail.com
Tue Apr 15 03:05:50 PDT 2008


Bill Baxter Wrote:

> Can you be more specific on how to deal with the _r variants of operator 
> overloads?

I never thought of explicit definitions of _r operators, point taken. But it can easily be amended:

    Foo op_reverse(+, -, *, /)(Foo value) {...}

the op_reverse keyword resembles the existing foreach_reverse. In the BlockStatement the keyword would be still "op" as it's shorter and melts into code more naturally.


> The first con that comes to my mind is
> * Sometimes you want to explicitly call an overloaded operator by name, 
> or get a delegate for it to pass to another function.

I never wanted the new syntax to replace the old one, but to amend it. The old one would be used like explicit memory management - rare, but available if one needs.


> Also Walter doesn't like treating the operator symbols as pure symbols. 
>   Part of the reason he gave the D operator overloads names like "opAdd" 
> was to discourage people from trying to overload "+" to mean anything 
> other than addition.  So your proposal will face an uphill battle 
> because of that.

Frankly, I think in the current system nothing but common sense stops you from writing:

    int opAdd(int i)
    {
        int targetsHit = 0;
        while (--i > 0)  targetsHit += LaunchNuclearMissle;
        return targetsHit;
    }

And the new proposal does, because it replaces "op" with an op symbol from the list and it can be *nothing else* but that symbol. If you want several ops overloaded at a time, it's hard to get the overloads to mean anything else than the original ops on a type's fields. So I think it's a good way to turn programmers' laziness into code that follows recommended guidelines:)


> Macros also might be able to provide this kind of thing.  Someday, when 
> they exist, that is.

Can you point me to a description of macros implementation-to-be in D? Can't find them on the DM website.


Tomek




More information about the Digitalmars-d mailing list