[fpc-devel] Templates / Generics Syntax

Peter Vreman peter at freepascal.org
Fri Nov 4 14:45:01 CET 2005

> Micha Nelissen wrote:
>> <code>
>> type
>>   TGenericCollection = generic(T: TCollectionItem) class(TComponent)
>>   ...implement TCollection and use T
>>   end;
>>   TCollection = TGenericCollection of (TCollectionItem);
>>   TFieldDefs = TGenericCollection of (TFieldDef);
>> </code>
> So generic procs could look like:
> <code>
> function generic(T: TTreeItem) MyFunc(A: T): T;
> begin
>   // do something with the tree item
> end;
> </code>
> My restrictions won't allow implementing generic Max and Min, I guess.
> That really needs macro-alike stuff (for the compiler implementation).
> The syntax could look like:
> <code>
> function generic(T) Max(A, B: T): T;
> begin
>    if A < B then
>      Result := B
>    else
>      Result := A;
> end;
> </code>

I did some tests with g++. It looks like it parses the template 'normally'
and don't handle it like a macro. When instantiating the template the
generic type is replaced.

I don't know if that is possible with FPC. The parser relies a lot on
types being available. Writing a special parser for generics is possible.
It can then store a simple expression/statement tree that will generate a
full node tree when the generic is instantiated. But that means that it
must be known that

More information about the fpc-devel mailing list