Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator not applicable to this operand type

i have this situation:

type
  TWheel = record
  private type
    TWheelEnum = (whBA, whCA, whFI, whGE, whMI, whNA, whPA, whRM, whRN,
      whTO, whVE);
  var
    FWheelEnum: TWheelEnum;
  public
    class operator Implicit(const Value: string): TWheel;
    class operator Implicit(const Value: TWheel): string;
  end;

with:

var
 awheel, bwheel: twheel;
begin
  try
    awheel := 'PA';
    bwheel := 'PA';
    if awheel = bwheel then writeln ('pippo');
end.

When i run it turn me this error:

E2015 Operator not applicable to this operand type

i have solved writing:

if awheel = string(bwheel) then writeln ('pippo');

but is possible solve it without add string(...)? In a first moment i have thinked something as:

class operator Implicit(const Value: TWheel): Twheel;

but compiler turn me error, telling that only one TWheel type is accepted. So i wanted know if there is a solution for it, or if i need use conversion type with string(...)? Thanks very much.

like image 819
Marcello Impastato Avatar asked Feb 23 '23 07:02

Marcello Impastato


1 Answers

You need to define an Equal operator:

class operator Equal(const a, b: TWheel): Boolean;

I guess the implementation should be:

class operator TWheel.Equal(const a, b: TWheel): Boolean;
begin
  Result := a.FWheelEnum=b.FWheelEnum;
end;

You will probably also want to implement the NotEqual operator.

class operator TWheel.NotEqual(const a, b: TWheel): Boolean;
begin
  Result := a.FWheelEnum<>b.FWheelEnum;//could write not (a=b) instead
end;

The definition of these operators is, in fact, enough for the compiler to accept equality comparison with mixed TWheel and string operands.

The full list of operators is provided in the documentation and it's well worth a read once in a while to reacquaint yourself with what is available in way of operator overloading.

like image 59
David Heffernan Avatar answered Mar 08 '23 05:03

David Heffernan