Operator overloading
The Anh Tran
trtheanh at gmail.com
Sat Dec 27 13:54:16 PST 2008
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) {}
Binary op: logic f1 || f2 && f3
bool operator(&&, ||, &, |, &)(Op[] oops, Foo[] foo)
{
auto result = foo[0].value;
foreach (i, op ; oops)
result = op( result, foo[i+1].value );
return result;
}
Binary op: bitwise
auto operator(&, |, ^)(Op[], Foo[]) {}
Binary op: add, sub, mul, div, shift, cat(~) f1 + f2 * f3 ~ f4
auto operator(+, -, *, /, %, <<, >>, ~, =)(Op[] oops, Foo[] foo()
{
auto result = foo[0].value;
foreach (i, op ; oops)
result = op( result, foo[i+1].value );
return result;
}
Op[], Foo[] should/may be re-arranged according to operator precedence???
Binary op: +=, -=, *=, <<=, ~= f1 *= f2 + f3 / f4
I 'think' the compiler can evaluate to: f1 = f1 * (f2 + f3 / f4);
More information about the Digitalmars-d
mailing list