Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a workaround to make class operators work for built-in types

I can use class operators for strings using an intermediate holding record.
So that I can so implicit conversion of built-in types.

program TestNewStringHelper; 
{$APPTYPE CONSOLE}
uses
  System.SysUtils;
type
  TStringRecord = record
  private
    Data: string;
  public
    class operator Implicit(const a: TStringRecord): Integer; inline;
    class operator Implicit(const a: string): TStringRecord; inline;
  end;

{ TStringRecord }

class operator TStringRecord.Implicit(const a: string): TStringRecord;
begin
  pointer(Result.Data):= pointer(a);
end;

class operator TStringRecord.Implicit(const a: TStringRecord): Integer;
begin
  Result:= StrToInt(a.Data);
end;

var
  input: TStringRecord;
  output: integer;

begin
  input:= '42';
  output:= input;
  WriteLn(IntToStr(output));
  ReadLn;
end.

I would like to do something like instead:

var
  input: string;
  output: integer;

begin
  input:= '42';
  output:= input;  //Class operator magic
  WriteLn(IntToStr(output));
  ReadLn;
end.

According to the online help:

Note: Class and record helpers do not support operator overloading.

and http://qc.embarcadero.com/wc/qcmain.aspx?d=72253

Is there a workaround to achieve implicit conversion of built-in types without using an intermediary type?

like image 613
Johan Avatar asked Mar 17 '23 03:03

Johan


1 Answers

Record and class helpers are the only way to extend the method scope for existing types. And helpers do not admit operator overloading.

The only point at which you can define overloading operators is whilst defining the type.

like image 96
David Heffernan Avatar answered Apr 20 '23 00:04

David Heffernan