[fpc-pascal] Can it map class type as key?

JC Chu jcchu at acm.org
Thu Apr 26 11:14:38 CEST 2012


It fails because the operators < and > are not defined for TObject,
which is assumed by TFPGMap<TKey, TValue>.KeyCompare().

As a makeshift you can implement a record type to wrap TObject and
define these operators for it.  See the attached file for an example.

Hope it helps.


On April 26, at 16:45, ZHANG Dao-yuan wrote:

>> program moi;
>> {$mode objfpc}
>>     uses fgl;
>>     type
>>         tSI= specialize tFpGMap<integer, tObject>;
>>         // tIS= specialize tFpGMap<tObject, integer>;
>> begin
>> end.
> 
> Hi,
> I'm trying to use template in fpc 2.6.0. I can map class type as value
> as above code can be compiled. But if I uncomment the declaration of tIS
> -- map class type as key, fpc fail to compile and print out these error
> msgs:
> 
> Error: Operator is not overloaded: "TObject" < "TObject"
> Error: Operator is not overloaded: "TObject" > "TObject"
> t.pas(10) Fatal: There were 2 errors compiling module, stopping
> Fatal: Compilation aborted
> Error: /usr/bin/ppcx64 returned an error exitcode (normal if you did not
> specify a source file to be compiled)
> 
> Any way to resolve it?
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal

-- 
Best Regards,
JC Chu
-------------- next part --------------
{$MODE DELPHI}

uses Fgl;

type
  TObjectRec = record
    Value: TObject;
    class operator LessThan(lhs, rhs: TObjectRec): Boolean;
    class operator GreaterThan(lhs, rhs: TObjectRec): Boolean;
    class operator Implicit(obj: TObject): TObjectRec;
    class operator Implicit(rec: TObjectRec): TObject;
  end;

  TTest = TFPGMap<TObjectRec, Integer>;

class operator TObjectRec.LessThan(lhs, rhs: TObjectRec): Boolean;
begin
  Exit(NativeInt(lhs) < NativeInt(rhs));
end;

class operator TObjectRec.GreaterThan(lhs, rhs: TObjectRec): Boolean;
begin
  Exit(NativeInt(lhs) > NativeInt(rhs));
end;

class operator TObjectRec.Implicit(obj: TObject): TObjectRec;
begin
  Result.Value := obj;
end;

class operator TObjectRec.Implicit(rec: TObjectRec): TObject;
begin
  Exit(rec.Value);
end;

begin
end.


More information about the fpc-pascal mailing list