Operator overloading

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Sat Dec 27 14:56:19 PST 2008


The Anh Tran wrote:
> Andrei Alexandrescu wrote:
>>>     auto op(++)(); // bar++
>>>     auto op(++)(int); // ++bar
>>
>> Hey, wasn't the implementation of the postincrement operator through 
>> an overload a rather untasty hack?
> 
>> Aside for a minor change in notation, there's no improvement. We're 
>> looking for much more broad improvements, such as offering the ability 
>> to overload several operators with only one function.
>>
>> Andrei
> 
> How about this:
> 
> Unary op: ++f, ~f, ~f, +f, -f, *f
> auto operator(++, --, ~, !, +, -, *)()
> {
>     // posfix is provided by compiler
>     // and is only used for: foo++ foo--
>     static if (posfix)
>         return op(this.value);
>     else ...
> }
> 
> Binary op: equality comparison f1 <= f2
> bool operator(<, >, <=, >=, ==, !=)(Foo foo)
> {
>     return op(this.value, foo.value);
> }
> 
> For un-order object, he/she just list 'correct' operator(s) in op() 
> list. Ex: bool operator(!=, ==)(Foo foo) {}

Why invent new syntax when compile-time strings are already there?

auto operator(string op)() if (op == "++" || op == "--")
{
     return mixin(op ~ "this.value");
}

etc. That, of course, is orthogonal to the semantic equivalences 
suggested by Don and does not solve fusion.

Andrei



More information about the Digitalmars-d mailing list