Automatic translation of opUnary!"++" into opOpAssign!"+"

monarch_dodra monarchdodra at gmail.com
Sat Dec 28 11:00:57 PST 2013


On Saturday, 28 December 2013 at 15:37:06 UTC, Francesco 
Cattoglio wrote:
> So, while I was studying the apropriate template constraints 
> for my shiny new iota implementation, I found out this funny 
> thing:
>
> import std.stdio;
>
> class Test{
>     int x = 41;
>     Test opOpAssign(string op)(int rhs) if (op == "+") {
>          x += rhs;
>          return this;
>     }
> }
>
> void main() {
>     Test t1 = new Test;
>     //class Test has no opUnary defined, so the following
>     //gets automagically converted into (t1) += (1)
>     ++t1;
>     writeln(t1.x); //prints 42, correct!
> }
>
> This actually comes really handy, but I couldn't find it into 
> the language documentation on dlang.org, so it surprised me.
> Did I miss it in the language specification? Should we add it 
> somewhere to the docs?
> Anyone with some spare time care to explain briefly what was 
> the rationale behind this?

I seem to remember that this is mentioned in TDPL? That's not 
spec of course, but I think it's mentioned here.

I'm a bit fuzy about the shortcuts, but I *think* there are a 
couple other shortcuts like this, such as "a += b" => "a = a + b"?

In any case, "http://dlang.org/operatoroverloading.html" needs to 
be updated


More information about the Digitalmars-d-learn mailing list