On Sunday, 22 June 2025 at 15:04:27 UTC, matheus wrote:
>Hi, could someone please tell me why operador overloading (https://dlang.org/spec/operatoroverloading.html) is relegated only to classes and structs?
One reason is that it would be hard to reason about what the operator means - for example if there is one operator overload in module a
and another one in b
, that have compatible operand types, and both imports are used in the same project for different modules.
Restricting operator overloading to the type definition avoids this problem.
That in itself might not be too much of a problem, but then any expression may implicitly convert to a type that has an operator overload defined. It can get hard to see what is going on, and free function operator overloads would complicate this.
>"1 Operator overloading is accomplished by rewriting operators whose operands are class or struct objects into calls to specially named members. No additional syntax is used."
I'd like to overload "~" to concatenate a string with a integer and do something else, like:
auto s = "1" ~ 2;
That is already valid code, because int
implicitly converts to dchar
, which can be appended to a string. E.g. "1" ~ 42
gives "1*"
. (BTW I don't think integer types should implicitly convert to character types). I trust you see how implicit conversions can get complicated in combination with operators.