Reputation: 29
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?
Upvotes: 1
Views: 203
Reputation: 29
Turns out the answer leads to solutions that get quite convoluted. There's a reason for strong typing! Because one cannot have multiple function return types with the same function name, one gets bogged down in similarly named functions for different argument types. If you try
var
mypointer : pointer;
begin
case argtype of
integer: mypointer := @A;
single : mypointer := @B;
end;
then you still need to type mypointer every time you use it. Turns out not to help a whole lot.
Upvotes: 1
Reputation: 80325
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;
Upvotes: 3