No implicit opOpAssign for structs with basic types?

Steven Schveighoffer schveiguy at gmail.com
Sat Apr 4 15:47:24 UTC 2020


On 4/4/20 8:14 AM, Robert M. Münch wrote:
> On 2020-04-04 10:32:32 +0000, Ferhat Kurtulmuş said:
> 
>> struct S {
>>      float a;
>>      float b;
>>
>>      S opOpAssign(string op)(ref S rhs) if (op == "+"){
>>          this.a += rhs.a;
>>          this.b += rhs.b;
>>          return this;
>>      }
>> }
> 
> If the struct is from some 3rd party source, how can I add such an 
> operator overloading to it? Is it possible to "extend" a struct later?
> 

No. operators must be implemented by the type itself. That is 
intentional (so types always act the same no matter where you import 
them). The only exception is UFCS, which doesn't cover operator overloading.

However, you can make a wrapper and use alias this.

-Steve


More information about the Digitalmars-d-learn mailing list