Question

It is possible to have a parameter in a routine which can be in the same time either an type, either an string? I know I can accomplish this by overloading a routine, I ask if it possible to do it in another way.

Assume that I have this type - TTest = (t1,t2,t3). I want to have a routine which accepts a parameter of type TTest, but in the same time to be a String, so I can call it myproc(t1) or myproc('blabla')

Was it helpful?

Solution 2

Even this can be easily accomplished with overloaded functions, considering it's a good exercise, based on David Hefferman's and Sertac Akyuz answers I made a small example to test both solutions. It is not perfect, it only shows both possibilities.

unit Unit4;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  ttest = (t1,t2);
  TForm4 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    function my(aVar:Variant):String;
    function MyUntype(const aVar):String;
  end;

var
  Form4: TForm4;

implementation

{$R *.dfm}

{ TForm4 }

procedure TForm4.FormCreate(Sender: TObject);
var aTestTypeVar : ttest;
    aString : String;
begin
 my(t1);
 my(t2);
 my('ssss');
//with untyped params
 aString := 'aaaa';
 MyUntype(aString);
 aTestTypeVar := t1;
 aString := IntToStr(Ord(aTestTypeVar));
 MyUntype(aString);//can not be a numeral due to delphi Help
end;

function TForm4.my(aVar: Variant): String;
begin
 showmessage(VarToStr(aVar));//shows either the string, either position in type
end;

function TForm4.MyUntype(const aVar): String;
begin
 //need to cast the parameter  
 try
  ShowMessage(pchar(aVar))
 except
  showmessage(IntToStr(Ord(ttest(aVar))));
 end;
end;

end.

Also I know that Variants are slow and must be used only needed.

OTHER TIPS

You should use an overloaded function.

You already have the perfect solution to the problem and there is no need to look for a different way to do this. You could try with a single function that receives a Variant, but then that function will also receive anything which means that the following would also be legal:

myproc(0.5);
myproc(intf);
myproc(-666);

Using an overload allows you to maintain compile time type safety and there is absolutely no loss of generality in using an overload.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top