www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Operator Overloading + / ~

reply Martin Tschierschke <mt smartdolphin.de> writes:
Just a thought it might be useful for cut-n-paste when porting 
code:

Would it be possible to define an operator overloading for 
'+'-Operator for strings to work as append? (like ~).
I understand, that '~' is in general a better choice than '+', so 
this is of more theoretical interest.
It is clear to me, that when I define my own string type this is 
possible.

Regards mt.
Jun 19
next sibling parent reply ketmar <ketmar ketmar.no-ip.org> writes:
Martin Tschierschke wrote:

 Just a thought it might be useful for cut-n-paste when porting code:

 Would it be possible to define an operator overloading for '+'-Operator 
 for strings to work as append? (like ~).
 I understand, that '~' is in general a better choice than '+', so this is 
 of more theoretical interest.
 It is clear to me, that when I define my own string type this is possible.

 Regards mt.
nope. it is not possible to overload operators for built-in types (and string is just an aliased array).
Jun 19
parent Martin Tschierschke <mt smartdolphin.de> writes:
On Monday, 19 June 2017 at 12:22:43 UTC, ketmar wrote:
 Martin Tschierschke wrote:

 Just a thought it might be useful for cut-n-paste when porting 
 code:

 Would it be possible to define an operator overloading for 
 '+'-Operator for strings to work as append? (like ~).
 I understand, that '~' is in general a better choice than '+', 
 so this is of more theoretical interest.
 It is clear to me, that when I define my own string type this 
 is possible.

 Regards mt.
nope. it is not possible to overload operators for built-in types (and string is just an aliased array).
Thank you for lightning fast response :-)
Jun 19
prev sibling parent Steven Schveighoffer <schveiguy yahoo.com> writes:
On 6/19/17 8:16 AM, Martin Tschierschke wrote:
 Just a thought it might be useful for cut-n-paste when porting code:
 
 Would it be possible to define an operator overloading for '+'-Operator 
 for strings to work as append? (like ~).
 I understand, that '~' is in general a better choice than '+', so this 
 is of more theoretical interest.
 It is clear to me, that when I define my own string type this is possible.
 
 Regards mt.
 
Just a further note, there is a reason + is not concatenation for arrays. does "1" + "1" = "2", or "11"? In some languages, both are possible outcomes, and which one is used depends on subtle differences in the context. With a specific operator to mean concatenation, the intent is clear. I would recommend you stick to using ~ for concatenation, even for your own types. -Steve
Jun 19