[fpc-devel] Generic class comparison operators

Benito van der Zander benito at benibela.de
Wed Apr 21 15:44:33 CEST 2021


  what about overloading operators for OBJECTs?

They do not conflict with any default operators.

I expected this to work, but it did not compile:

   type generic TXQHashset<TKey, TInfo> = object //(specialize 
     class operator =(const a, b: TXQHashset): boolean;

On 17.04.21 22:12, Jonas Maebe via fpc-devel wrote:
> On 2021-04-17 22:02, Ryan Joseph via fpc-devel wrote:
>> Since I'm working on generics right now can we finally, at the very
>> least, allow class operators for comparison operators? This is
>> literally the only way for a generic class to override the = operator
>> (along with some others) so there's no reason not to allow this. I
>> understand the objection to :=, + etc.. where it returns a copy of a
>> class instance and people could in theory do memory unsafe things,
>> with comparison operators there is no possibility for this. I already
>> made a patch for "advanced records" which is in limbo but It's trivial
>> to adapt this for classes and put restrictions on the type of
>> operator.
> The issue with allowing it for classes (generic or not) is that the 
> the = operator already has a meaning for them (pointer equality). I 
> think in general we don't allow overloading operators that have a 
> built-in meaning.
> It would work very well either, because if you'd pass such a class 
> instance as a TObject parameter and that called routine performs a 
> comparison, then suddenly the comparison would happen again based on 
> pointer equality rather than with this custom operator. This means 
> that e.g. any non-generic container class that uses comparisons (for 
> sorting or for detecting duplicates) would fail to work, or at least 
> work differently than generic container classes. That's something you 
> don't want at all in a programming language, as it means you 
> constantly have to keep in mind how something you call was implemented 
> to know how it will behave (the called routine may even have your 
> class type as parameter type, but then call something else that uses 
> TObject).
> Jonas
> _______________________________________________
> fpc-devel maillist  -  fpc-devel at lists.freepascal.org
> https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-devel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20210421/c2f97b13/attachment.htm>

More information about the fpc-devel mailing list