Is there a way to overload a function based on dif

2019-04-07 17:40发布

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?

3条回答
Juvenile、少年°
2楼-- · 2019-04-07 18:21

You can take the "result" as a parameter.

procedure Blah( InVar : word; out OutVar : Byte ); overload;
procedure Blah( InVar : word; out OutVar : String ); overload;
查看更多
爷、活的狠高调
3楼-- · 2019-04-07 18:26

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;
查看更多
来,给爷笑一个
4楼-- · 2019-04-07 18:32

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);
查看更多
登录 后发表回答