[fpc-devel] Generic class comparison operators

Jonas Maebe jonas at freepascal.org
Sat Apr 17 22:12:06 CEST 2021

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 

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).


More information about the fpc-devel mailing list