[PATCH] modeswitch for class operators
Original Reporter info from Mantis: ryan_joseph @genericptr
-
Reporter name: Ryan Joseph
Original Reporter info from Mantis: ryan_joseph @genericptr
- Reporter name: Ryan Joseph
Description:
Full source at: https://github.com/genericptr/freepascal/tree/classops.
I'd like to propose a minor, non-invasive mode switch to allow "class operator" to extend to classes and objects (now only available in records and "operator functions"). Class operators introduce memory management complications so a mode switch is used to allow users to opt in explicitly. However, operator functions don't require a mode switch for classes so the functionality has already been introduced without any safety checks. I believe this was basically smuggled in as a side affect of function operators so I contend that users should be allowed to opt in to a more powerful syntax since the feature already basically exists, albeit in a worse syntax.
Some notes:
-
Relational, "in" and "not" unary operators have no inherit memory management implications so they are 100% safe.
-
For arithmetic operators like += the class can be muted and safely returned without any implications. Otherwise returning copies of classes is only safe for users that have some kind of memory management system that defers freeing (like deferred release memory pools). Having said that arithmetic operators on classes probably doesn't make sense and is better left in the domain of records/objects.
2A) Arithmetic binary operators can be reversed so the class type is not returned thus not introducing any memory management issues. I'm not aware of any use for this but it is possible so presumably it could be used to some benefit.
- Class operators for generics can now work properly. I personally needed this so that I could add the += operator to collection classes so they behave like dynamic arrays, i.e.:
type
TIntegerList = TList<integer>;
var
arr: TIntegerList;
begin
arr := TIntegerList.Create;
arr += 1;
end.
-
Adds operators to old-style objects (100% safe like in advanced records).
-
Currently doesn't work in Delphi mode because operator functions are not supported in Delphi mode.
Tests are not that great so I'll add more later if any of this gets approved.
Additional information:
// basic example program
{$mode objfpc}
{$modeswitch classoperators}
program test;
type
generic TGList<T> = class
value: integer;
class operator = (left: TGList; right: T): boolean;
end;
class operator TGList.= (left: TGList; right: T): boolean;
begin
result := (left.value = right);
end;
type
TIntegerList = specialize TGList<integer>;
var
c: TIntegerList;
begin
c := TIntegerList.Create;
if c = 100 then
writeln('is 100');
end.
Mantis conversion info:
- Mantis ID: 35457
- Version: 3.3.1