[fpc-devel] Templates / Generics
dannym
danny.milo at gmx.net
Tue Nov 8 18:47:49 CET 2005
Hi,
Am Freitag, den 04.11.2005, 19:33 +0100 schrieb Peter Vreman:
> At 18:17 4-11-2005, you wrote:
> >This is evaluated by the pre-compiler run during compile time.
> >
> >When you use the template with e.g.
> >var
> >bl: List<String>;
> >
> >then procedure show(s:string) is taken.
> >
>
> But what if the bl: List<String> is called from an other unit? The
> Show(string) is then not visible anymore?
Put the Show(string) into the ppu too, with a mangled name, and save any
calls of Show within the generic type implementation to the ppu, writing
the mangled name.
Excuse the stupid made-up example below, but I can't think of anything
that really _needs_ global functions right now, so I cheated by using
class functions and a global catch-all variable to require a global
translation function:
unit ubaz;
interface
type
TCache = generic(T: TObject) class(TObject)
published
class procedure Put(Name: string; Instance: T);
class function Get(Name: string): T;
end;
implementation
var
gCachedObjects: array of TObject;
gCachedNames: array of string;
function FooToBar(Name: string; Instance: TObject): string;
begin
Result := T.ClassName + '_' + Name;
end;
class procedure TCache.Put(Name: string; Instance: T);
begin
SetLength(gCachedObjects, Length(gCachedObjects) + 1);
SetLength(gCachedNames, Length(gCachedNames) + 1);
gCachedObjects[High(gCachedObjects)] := Instance;
gCachedNames[High(gCachedNames)] := FooToBar(Name, Instance);
end;
class function TCache.Get(Name: string): T;
var
i: Integer;
begin
Result := nil;
for i := 0 to High(gCachedNames) do begin
if gCachedNames[i] = Name then begin
if gCachedObjects[i] is T then begin
Result := gCachedObjects[i];
end;
Break;
end;
end;
end;
end.
the generated ppu should have
$Private$FooToBar$string$TObject: function ($2843423)
and the generic parts:
....
gCachedNames[High(gCachedNames)] := uBaz.$Private$FooToBar(Name,
Instance);
Or did I miss something important ? (apart from the act of
auto-publishing of the function although it is not in the interface
section being a bit evil)
cheers,
Danny
[...]
More information about the fpc-devel
mailing list