No implicit opOpAssign for structs with basic types?

Steven Schveighoffer schveiguy at gmail.com
Sat Apr 4 15:45:52 UTC 2020


On 4/4/20 8:07 AM, Robert M. Münch wrote:
> On 2020-04-04 10:32:32 +0000, Ferhat Kurtulmuş said:
> 
>> Probably I didn't understand what you mean. Sorry if this is not the 
>> case, but this one is easy.
>> ...
>> 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;
>>      }
>> }
>>
>>
>> void main()
>> {
>>      S a = {1, 5};
>>      S b = {2, 5};
>>
>>      a += b;
>>
>>      writeln(a);
>> }
>> ...
> 
> Yes, sure, but in C++ I don't have to explicitly write this down. It 
> just works. IMO that makes a lot of sense as long as all types fit. This 
> just looks superfluously.
> 

steves at homebuild:~$ cat test.cpp
struct S
{
	float a;
	float b;
};
int main()
{
	S a = {1, 5};
	S b = {2, 5};
	
	a += b;
}
steves at homebuild:~$ g++ -o test test.cpp
test.cpp: In function ‘int main()’:
test.cpp:11:4: error: no match for ‘operator+=’ (operand types are ‘S’ 
and ‘S’)
   a += b;
   ~~^~~~

Doesn't seem to "just work" for me...

-Steve


More information about the Digitalmars-d-learn mailing list