I'm working on a problem in which I need to dynamically size an array, upon which numerous operations are needed. I have successfully coded two classes, t_one and t_two:
tarray1 : array of longint;
tarray2 : array of single;
t_one = class(tobject)
Public
Myarray1 : tarray1;
constructor create;
destructor destroy;
procedure oneofmany;
end;
t_two = class(tobject)
Public
Myarray1 : tarray2;
constructor create;
destructor destroy;
procedure oneofmany;
end;
The two objects have nearly identical code except that Myarray1 is an array of single in one case and an array of longint in the other. Is the only way to make this into a single object to use variant arrays (which will slow things down)? A variant record is inefficient for what I'm doing as well. If I could say
case mysituation of
integerdata : (myarray1 : tarray1);
realdata: (myarray1 : tarray2);
end;
that would be what I mean, but obviously that syntax is anathema. Of course, there are places where method calls and function results need to know the data type, but once defined they're consistent. Thoughts? Use a variant array and suffer the slowdown?
One of possible approaches - make the only class using generics
TA<T> = class
public
Arr : TArray<T>;
destructor destroy;override;
end;
...
procedure TForm1.Button1Click(Sender: TObject);
var
A: TA<Integer>;
B: TA<Single>;
begin
A := TA<Integer>.Create;
B := TA<Single>.Create;
A.Arr := [1,2,3];
B.Arr := [Pi, Ln(2)];
Memo1.Lines.Add(A.Arr[0].ToString);
Memo1.Lines.Add(B.Arr[0].ToString);
end;