Global Operator Overloads
Peter Alexander
peter.alexander.au at gmail.com
Sun Oct 20 04:15:11 PDT 2013
This seems to have been discussed a couple of times in the past,
but nothing appears to have come of it.
I have read the rationale against global operator overloads
(http://dlang.org/rationale.html) but the arguments are weak. The
first argument is that stylistically, operators belong as
members, and the second is that operators often need private
member access. The first "argument" is just opinion, and the
second is simply false in most cases I can think of. Even if the
second were true, it's not an argument against global operators
since overloads in the same module would have access.
There are at least three benefits to allowing global operator
overloads:
1. Consistency. Operators are just functions with special syntax.
Semantically, there should be no difference between (a + b) and
add(a, b), so why must the operator be a member function of 'a'
while 'add' can be global?
2. Genericity: By restricting operators to member functions, you
cannot define operators that work across a number of different
types.
3. Extensibility: By restricting operators to member functions,
you cannot add operators to types that have forgotten to define
them if you don't have access to the source.
Some motivating examples for genericity:
bool opEquals(R1, R2)(R1 a, R2 b)
if (isInputRange!R1 && isInputRange!R2)
{
return equal(a, b);
}
auto opBinary(string op, T)(T x, uint n)
if (op == "^^" && isMonoid!(T, "*"))
{
return exponentiationBySquaring(x, n);
}
auto opSliceAssign(R, T)(R r, T v)
if (isRandomAccessRange!R &&
hasLength!R &&
is(T : ElementType!R) &&
hasAssignableElements!R)
{
foreach (i; 0..r.length)
r[i] = v;
}
(please forgive any mistakes in the examples, I haven't tested
them or spent too long thinking about them)
I think D would benefit from allowing global operator overloads.
Semantically they should work just like global functions, i.e.
lookup prefers member functions if available, and fall back to
global functions otherwise. I don't believe there are any
backwards-compatibility issues.
More information about the Digitalmars-d
mailing list