Compound assignment operators

Yao G. yao.gomez at spam.gmail.com
Wed Aug 25 22:31:38 PDT 2010


Sorry, I sent the message prematurely :( Anyway, here's complete:

Is there a way to make compound assignment operators (-=, +=, *= and
friends) work with D's operator overload regime? I can't make them work.

> struct Foo
> {
>     this( int bar ) {
>          bar = bar;
>     }
>
>     Foo opBinary(string op)( in typeof(this) rhv )
>     if( op == "+=" )
>     {
>          _bar += rhv._bar;
>          return this;
>     }
>
>     private int _bar;
> }
>
> void main()
> {
>     auto f1 = Foo(1);
>     auto f2 = Foo(2);
>     f2 += f1;

I get the following compiler error:

> Error: 'f1' is not a scalar, it is a Foo
> Error: 'f1' is not of arithmetic type, it is a Foo
> Error: 'f2' is not of arithmetic type, it is a Foo

Is there a way to make this work? Even changing the operator string in  
opBinary to "-" doesn't do nothing. Or those kind of operators can't be  
overloaded?

-- 
Yao G.


More information about the Digitalmars-d-learn mailing list