是否有使 class 运算符适用于内置类型的解决方法
Is there a workaround to make class operators work for built-in types
我可以对使用中间持有记录的字符串使用 class 运算符。
这样我就可以对内置类型进行隐式转换。
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.
我想做类似的事情:
var
input: string;
output: integer;
begin
input:= '42';
output:= input; //Class operator magic
WriteLn(IntToStr(output));
ReadLn;
end.
根据联机帮助:
Note: Class and record helpers do not support operator overloading.
和http://qc.embarcadero.com/wc/qcmain.aspx?d=72253
是否有解决方法可以在不使用中间类型的情况下实现内置类型的隐式转换?
Record 和 class 助手是扩展现有类型方法范围的唯一方法。并且 helpers 不允许运算符重载。
唯一可以定义重载运算符的地方是在定义类型时。
我可以对使用中间持有记录的字符串使用 class 运算符。
这样我就可以对内置类型进行隐式转换。
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.
我想做类似的事情:
var
input: string;
output: integer;
begin
input:= '42';
output:= input; //Class operator magic
WriteLn(IntToStr(output));
ReadLn;
end.
根据联机帮助:
Note: Class and record helpers do not support operator overloading.
和http://qc.embarcadero.com/wc/qcmain.aspx?d=72253
是否有解决方法可以在不使用中间类型的情况下实现内置类型的隐式转换?
Record 和 class 助手是扩展现有类型方法范围的唯一方法。并且 helpers 不允许运算符重载。
唯一可以定义重载运算符的地方是在定义类型时。