Operator Overloading

Top  Previous  Next

Smart Pascal supports operator overloading. It can be applied to every type, classes included. You can overload all binary operators (+, *, etc.). The declaration syntax is as follows:

 

operator  <op>(<typeLeft>,<typeRight>): <typeResult> uses <someFunc>; 

 

Operator overloading is considered a form of syntax-sugar, and treated as such, ie. you have to provide a regular function to handle the processing, the operator is just an alias for that function.

There are three extra operators - <<, >> and ˆ, which can additionally be used at statement level (unlike regular binary operators). By default those three operators do nothing, they’re available for operator-overloading purposes only.

 

Smart Pascal also supports class operator overloading. The syntax differs from Delphi, FreePascal & Prism in that they are not special methods/procedures, but syntax-sugar aliases, in a fashion similar to what properties achieve.

 

   class  operator  <operator>  <rightType>  uses  <method>

 

To illustrate this with TList, you could declare.

 

   class  operator  +=  TObject  uses  Add;
   class  operator  -=  TObject  uses  Remove;

 

After that, myList  +=  item would be equivalent to myList.Add(item).

Class operators support type overloading. It is thus possible to declare:

 

   TMyClass  =  class
   procedure  AddInteger(i:  Integer);
   procedure  AddString(s:  String);
 
   class  operator  +=  Integer  uses  AddInteger;
   class  operator  +=  String  uses  AddString;
   end;

 

The method will be selected depending on the operand type:

 

   myObject  +=  10;  //  will  use  AddInteger
   myObject  +=  'ten';  //  will  use  AddString;