static / global operator overload
monarch_dodra
monarchdodra at gmail.com
Sun Aug 18 09:42:08 PDT 2013
On Sunday, 18 August 2013 at 15:29:26 UTC, Ali Çehreli wrote:
> On 08/18/2013 07:34 AM, Namespace wrote:
>
> > In C++ you can declare operator overloads inside and outside
> of classes
> > (the latter is more popular)
>
> The latter is popular because a global operator takes advantage
> of implicit type conversions. A global operator+ allows using
> an int even on the left-hand side of the operator.
>
> As a result, assuming that MyInt can be constructed from an
> int, when there is
>
> // Assume this is defined outside of MyInt definition
> MyInt operator+(MyInt lhs, MyInt rhs);
>
> the expression
>
> 1 + MyInt(2)
>
> is lowered to
>
> operator+(MyInt(1), MyInt(2))
>
> > so why wasn't this introduced in D also?
>
> My guess is that there is no implicit construction of objects
> in D anyway so there wouldn't be that benefit.
>
> Ali
D defines the member "opBinaryRight", which makes global
operators un-needed.
//====
struct S
{
void opBinary(alias s)(int i)
if (s == "+")
{
writeln(s);
}
void opBinaryRight(alias s)(int i)
if (s == "+")
{
return this + i;
}
}
void main()
{
S s;
s + 5;
5 + s;
}
//====
Doing this also helps avoid poluting the global name-space with
operators.
More information about the Digitalmars-d-learn
mailing list