开发者

Is there a way to overload a function based on different Result type in Delphi?

Function overloading by return type?

has a very detailed answer on the rational on function overloading by return type, and from what I can see Delphi does not allow this, but are there any workarounds to overload a function based on different开发者_运维技巧 return type in Delphi?


The implicit and explicit conversion operators for records permit overloading by return type: namely, the type being converted to:

type
  TFoo = record
    class operator Implicit(const AFoo: TFoo): Integer;
    class operator Implicit(const AFoo: TFoo): string;
  end;

Depending on the context, using a value of type TFoo will call the appropriate implicit conversion. If trying to use a value of type TFoo as an argument to an overloaded routine that can take either Integer or string in that position, an overload error will occur:

test.pas(33) Error: E2251 Ambiguous overloaded call to 'Q'
 + Test.pas(19) Related method: procedure Q(Integer);
 + Test.pas(24) Related method: procedure Q(const string);


You can take the "result" as a parameter.

procedure Blah( InVar : word; out OutVar : Byte ); overload;
procedure Blah( InVar : word; out OutVar : String ); overload;


I took the above idea and implemented it in a tokenreader used for importing data. Each token is a string, which is then converted to the appropriate type. The code needed for converting to integer and string is at the bottom of the post.

To read and convert a token only the following code is needed:

Myvalue := DataImporter.ImportToken;

Depending on the type of Myvalue, the correct implicit conversion is triggered.


The code:

TTokenValue = record
public
  FValue:string;
  constructor Create(const AValue:string);
  class operator Implicit(const AFoo:TTokenValue): integer;
  class operator Implicit(const AFoo:TTokenValue): string;
end;

Implementation

function TDataImporter.ImportToken: TTokenValue;
begin
  result := TTokenValue.Create(GetCurrentToken());
end;

constructor TTokenValue.Create(const AValue: string);
begin
  FValue := AValue;
end;

class operator TTokenValue.Implicit(const AFoo: TTokenValue): integer;
begin
  result := strtointdef(AFoo.FValue, 0);
end;

class operator TTokenValue.Implicit(const AFoo: TTokenValue): string;
begin
  result:=AFoo.FValue;
end;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜