Operator overloading
Operator overloading refers to re-defining already defined operators with new definitions. The term is – although imprecisely – used for operator definitions, that have not yet been defined, too.
overloadable operators
Almost all operators can be (re-)defined:
- assignment operators
- arithmetic operators
- comparison operators
- logical operators
- and the special operator
enumerator
.
The only operators that can not be overloaded are as
and is
.
definition
An operator is declared as if it was a function, with a few differences:
- Instead of the word
function
it starts withoperator
. - The function's identifier is always one of the available operators e.g.
><
, although this would not constitute a valid identifier anywhere else. - The parameter list has to name exactly one or two parameters, depending on the operator.
- A result identifier can be specified in front of the colon separating the result type, but can be omitted where the special identifier
result
is available.
The following shows a valid operator declaration.
operator := (x: myNewType) y: someOtherType;
Operators are defined the same way as any other function, by following the signature with a block.
routing
Which operator overload definition is chose differs in many aspects how a function is chosen.
- The assignment operator
:=
is used for implicit typecasts. - Unlike regular function overloads, assignment operator overloads are chosen by their result type.
- Operator overloads can not be chosen explicitly by their scope they are defined in. Something like
unitDefiningOverloads.+
is not possible. The last operator definition always wins and this can not be changed.
Operator overloads should be used with caution. They potentially make it harder to identify problems, since it is not necessarily obvious a operator overload applies.