Quote
Frens Vonken <J.F.Von...@pth.nl> wrote:
>In C++ there is the possibility to add a data template to a class
>declaration. With this construct the datatype of some variables can stay
>undeclared until a derived class is declared. In the declaration of
>several derived classes the datatype of the template can be assigned to
>different types.
>Does anyone know whether it is possible to create a similar thing in
>Delphi?
There is no compiler support for templates, but you can use class references
(aka metaclasses) to approximate their use. The following example shows a
"component generator" that takes a component class reference as a constructor
parameter, and will generate components of that component class:
----
interface
[...]
TComponentGenerator = class(TObject)
private
FCompClass: TComponentClass;
public
constructor Create(ACompClass: TComponentClass);
function Generate(AOwner: TComponent): TComponent;
end;
implementation
[...]
constructor TComponentGenerator.Create(ACompClass: TComponentClass);
begin
inherited Create;
FCompClass := ACompClass;
end;
function TComponentGenerator.Generate(AOwner: TComponent): TComponent;
begin
{ note that this works because TComponent's constructor is virtual }
Result := FCompClass.Create(AOwner);
end;
------
You could then use this class like the following:
procedure TForm1.Button1Click(Sender: TObject);
var
comp: TComponent;
compgen: TComponentGenerator;
begin
{ we want to generate buttons, so pass the button class to the Component
Generator constructor }
compgen := TComponentGenerator.Create(TButton);
{ now generate a button }
comp := compgen.Generate(self);
{ set button properties }
with comp as TButton do
begin
Parent := self;
Caption := 'A Generated Button!';
end;
compgen.Free;
end;
------
With similar techniques, you can create container classes. Let me know if you
have any questions...
--------------------------------------------------
brent_byso...@mindlink.bc.ca
VB, Delphi & SQL Development
Vancouver, BC.
(604) 689-2616
-------------------------------------------------