unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TXX }
generic TXX<T> = class
function Double(A: T): T;
end;
TXX_Integer = specialize TXX<Integer>;
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
o: TXX_Integer;
begin
o := TXX_Integer.Create;
ShowMessage(IntToStr(o.Double(10)));
end;
{$R *.lfm}
{ TXX }
function TXX.Double(A: T): T;
begin
Result := A + A;
end;
end.
最近突然想到C#中提到泛型与模板的区别,这样实现泛型是为了防止代码大量复制,当然功能上也就大打折扣了.要实现C++的模板功能,只能模仿DGL的方式了.将公共代码部分抽取到inc文件中,将变量类型作为替换部分即可实现.不过最终模板会为每个子类型维护一份代码拷贝.FreePascal应该也是这种原理吧.