Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi 'in' operator overload on a set

In Delphi XE2, I'm trying to overload the in operator on a record to allow me to check whether the value represented by the record is part of a set. My code looks like this:

type
  MyEnum = (value1, value2, value3);
  MySet = set of MyEnum;
  MyRecord = record
    Value: MyEnum;
    class operator In(const A: MyRecord; B: MySet): Boolean;
  end;

class operator MyRecord.In(const A: MyRecord; B: MySet): Boolean;
begin
  Result := A.Value in B;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  R: MyRecord;
  S: MySet;
begin
  R.Value := value1;
  S := [value1, value2];
  Button1.Caption := BoolToStr(R in S);
end;

The code fails to compile. For the statement R in S the compiler says: Incompatible types MyRecord and MyEnum.

How can I overload the In operator on MyRecord so that R in S will evaluate to True in the above code?

like image 259
Jan Goyvaerts Avatar asked Nov 08 '11 03:11

Jan Goyvaerts


1 Answers

For the in operator to work the right operand must be of the record type since it's a set operator and not a binary operator. In your case it is the left operand.

So the following will work:

type
  MyRecord = record
    Value: MyEnum;
    class operator In(const A: MyRecord; const B: MySet): Boolean;
  end;

  MyRecord2 = record
    Value: MySet;
    class operator In(const A: MyRecord; const B: MyRecord2): Boolean;
    class operator In(const A: MyEnum; const B: MyRecord2): Boolean;
  end;

class operator MyRecord.In(const A: MyRecord; const B: MySet): Boolean;
begin
  Result := A.Value in B;
end;

class operator MyRecord2.In(const A: MyRecord; const B: MyRecord2): Boolean;
begin
  Result := A.Value in B.Value;
end;

class operator MyRecord2.In(const A: MyEnum; const B: MyRecord2): Boolean;
begin
  Result := A in B.Value;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  R: MyRecord;
  R2: MyRecord2;
begin
  R.Value := value1;
  R2.Value := [value1, value2];

  if R in R2 then;
  if value1 in R2 then;
end;
like image 62
Stefan Glienke Avatar answered Oct 11 '22 00:10

Stefan Glienke